<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('t_qad_sync_logs', function (Blueprint $table) {
            $table->id();
            $table->enum('sync_type', ['stores', 'menus', 'all']);
            $table->enum('status', ['Running', 'Success', 'Failed', 'Partial'])->default('Running');
            $table->integer('total_from_qad')->default(0);
            $table->integer('total_inserted')->default(0);
            $table->integer('total_updated')->default(0);
            $table->integer('total_errors')->default(0);
            $table->json('error_details')->nullable();
            $table->json('sync_details')->nullable();
            $table->timestamp('started_at');
            $table->timestamp('completed_at')->nullable();
            $table->integer('duration_seconds')->nullable();
            $table->unsignedBigInteger('triggered_by')->nullable();
            $table->enum('trigger_type', ['manual', 'scheduled', 'api'])->default('manual');
            $table->integer('qad_response_time')->nullable()->comment('Response time in milliseconds');
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            // Indexes
            $table->index(['sync_type', 'status']);
            $table->index(['started_at']);
            $table->index(['trigger_type']);
            $table->index(['triggered_by']);

            // Foreign key constraints
            $table->foreign('triggered_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('t_qad_sync_logs');
    }
};
