<?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('import_rows', function (Blueprint $table) {
            $table->id();
            $table->foreignId('import_id')->constrained('imports')->cascadeOnDelete();

            $table->unsignedInteger('row_number');
            $table->string('sheet_name', 64)->nullable();

            // Type of record represented in this row (person, account, etc.)
            $table->string('record_type', 50)->nullable();

            // Data and results
            $table->json('raw_data')->nullable();
            $table->json('mapped_data')->nullable();
            $table->string('status', 20)->default('pending'); // pending|valid|invalid|imported|skipped
            $table->json('errors')->nullable();
            $table->json('warnings')->nullable();

            // Link to created entity (optional, polymorphic)
            $table->nullableMorphs('entity'); // entity_type + entity_id

            // Dedup/trace
            $table->string('fingerprint', 64)->nullable()->index();

            // Helpful indexes
            $table->index(['import_id', 'status']);
            $table->index(['import_id', 'row_number']);
            $table->index('record_type');

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

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