<?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
    {
        if (! Schema::hasTable('imports')) {
            Schema::create('imports', function (Blueprint $table) {
                $table->id();
                $table->uuid('uuid')->unique();

                // Who initiated the import
                $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();

                // Optional template applied to this import (FK can be added separately if needed)
                $table->foreignId('import_template_id')->nullable();

                // Optional client this import is for (many imports per client)
                $table->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete();

                // File/source metadata
                $table->string('source_type', 12); // csv|xml|xls|xlsx|json
                $table->string('file_name', 255);
                $table->string('original_name', 255)->nullable();
                $table->string('disk', 50)->default('local');
                $table->string('path', 2048);
                $table->unsignedBigInteger('size')->nullable(); // bytes
                $table->string('sheet_name', 64)->nullable(); // for Excel

                // Progress/status
                $table->string('status', 20)->default('uploaded'); // uploaded|parsing|parsed|validating|importing|completed|failed
                $table->unsignedInteger('total_rows')->default(0);
                $table->unsignedInteger('valid_rows')->default(0);
                $table->unsignedInteger('invalid_rows')->default(0);
                $table->unsignedInteger('imported_rows')->default(0);
                $table->timestamp('started_at')->nullable();
                $table->timestamp('finished_at')->nullable();
                $table->timestamp('failed_at')->nullable();

                // Diagnostics and flexibility
                $table->json('error_summary')->nullable();
                $table->json('meta')->nullable();

                // Helpful indexes
                $table->index('user_id');
                $table->index('import_template_id');
                $table->index('status');
                $table->index('client_id');
                $table->index('source_type');
                $table->index(['disk', 'path']);

                $table->timestamps();
                $table->softDeletes();
            });
        }
    }

    public function down(): void
    {
        // Only drop if this migration created it (to be safe if others depend on it)
        if (Schema::hasTable('imports')) {
            Schema::drop('imports');
        }
    }
};
