<?php

use App\Extensions\Concerns\ChecksExtensionInstallation;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    use ChecksExtensionInstallation;

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('importer_jobs', function (Blueprint $table) {
            $table->id();

            // Job identification
            $table->string('name')->nullable(); // User-friendly name for this import
            $table->enum('source', ['csv', 'database', 'supportpal']); // Import source
            $table->enum('type', ['customers', 'tickets', 'responses', 'announcements', 'departments', 'database']); // What we're importing
            $table->enum('status', ['pending', 'processing', 'completed', 'failed', 'paused'])->default('pending');

            // Progress tracking
            $table->integer('total_rows')->default(0); // Total rows to import
            $table->integer('processed_rows')->default(0); // Rows successfully imported
            $table->integer('failed_rows')->default(0); // Rows that failed
            $table->integer('current_offset')->default(0); // Current position (for resume)
            $table->integer('chunk_size')->default(100); // Rows per batch

            // Source details
            $table->string('file_path')->nullable(); // For CSV imports
            $table->json('db_config')->nullable(); // For database imports

            // Field mapping
            $table->json('field_mapping')->nullable(); // Column mappings

            // Options
            $table->json('options')->nullable(); // Import options (skip header, create users, etc)

            // Results
            $table->json('errors')->nullable(); // Error log
            $table->text('result_summary')->nullable(); // Summary message

            // Timestamps
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();

            // Indexes
            $table->index('status');
            $table->index(['source', 'type']);
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Skip rollback if extension is not installed
        if ($this->shouldSkipRollback('importer')) {
            return;
        }

        Schema::dropIfExists('importer_jobs');
    }
};
