<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('pwa_audit_logs', function (Blueprint $table) {
            $table->id();

            // Multi-tenant
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();

            // Who
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('device_id', 255)->nullable();
            $table->string('device_name', 255)->nullable();

            // What
            $table->string('action', 50)->index(); // login, logout, payment, sync, etc.
            $table->string('resource_type', 50)->nullable(); // payment, credit, etc.
            $table->unsignedBigInteger('resource_id')->nullable();

            // Context
            $table->string('channel', 20)->default('pwa'); // pwa, api, web
            $table->boolean('offline_action')->default(false);
            $table->timestamp('offline_created_at')->nullable();
            $table->uuid('idempotency_key')->nullable()->index();

            // Request metadata
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent', 500)->nullable();

            // Payload
            $table->json('request_data')->nullable();
            $table->json('response_data')->nullable();
            $table->json('metadata')->nullable();

            // Result
            $table->string('status', 20)->default('success'); // success, error, duplicate
            $table->text('error_message')->nullable();

            $table->timestamps();

            // Indexes for common queries
            $table->index(['company_id', 'user_id', 'created_at']);
            $table->index(['company_id', 'action', 'created_at']);
            $table->index(['resource_type', 'resource_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('pwa_audit_logs');
    }
};
