<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Spatie\Health\Models\HealthCheckResultHistoryItem;
use Spatie\Health\ResultStores\EloquentHealthResultStore;

/**
 * Consolidated import, export, and monitoring tables (squashed 2026-07-11).
 *
 * Each table is created once with its final schema, guarded with hasTable
 * checks so installs that predate the squash don't collide on CREATE TABLE.
 *
 * Do not add future schema changes to this file — fresh installs and
 * existing installs would diverge. Create a new migration instead.
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $this->createIfMissing('imports', function (Blueprint $table) {
            $table->id();
            $table->timestamp('completed_at')->nullable();
            $table->string('file_name');
            $table->string('file_path');
            $table->string('importer');
            $table->unsignedInteger('processed_rows')->default(0);
            $table->unsignedInteger('total_rows');
            $table->unsignedInteger('successful_rows')->default(0);
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->timestamps();
        });

        $this->createIfMissing('exports', function (Blueprint $table) {
            $table->id();
            $table->timestamp('completed_at')->nullable();
            $table->string('file_disk');
            $table->string('file_name')->nullable();
            $table->string('exporter');
            $table->unsignedInteger('processed_rows')->default(0);
            $table->unsignedInteger('total_rows');
            $table->unsignedInteger('successful_rows')->default(0);
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->timestamps();
        });

        $this->createIfMissing('failed_import_rows', function (Blueprint $table) {
            $table->id();
            $table->json('data');
            $table->foreignId('import_id')->constrained('imports')->cascadeOnDelete();
            $table->text('validation_error')->nullable();
            $table->timestamps();
        });

        $this->createIfMissing('queue_monitors', function (Blueprint $table) {
            $table->id();
            $table->string('job_id');
            $table->string('name')->nullable();
            $table->string('queue')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('finished_at')->nullable();
            $table->boolean('failed')->default(false);
            $table->integer('attempt')->default(0);
            $table->integer('progress')->nullable();
            $table->text('exception_message')->nullable();
            $table->timestamps();

            $table->index('job_id');
            $table->index('started_at');
            $table->index('failed');
        });

        $this->createHealthTable();
    }

    /**
     * Rollback is intentionally blocked.
     *
     * Squashed migrations consolidate the entire schema into one pass and have
     * no meaningful prior state to restore. Rolling back would drop live data
     * on existing installs, so rollback is intentionally blocked. Use
     * `php artisan migrate:fresh` to rebuild the schema from scratch on a
     * non-production database.
     */
    public function down(): void
    {
        throw new RuntimeException(
            'Squashed migrations cannot be rolled back. Run `php artisan migrate:fresh` to rebuild the schema on a non-production database.'
        );
    }

    /**
     * Create the spatie/health result history table on its configured connection.
     */
    private function createHealthTable(): void
    {
        $connection = (new HealthCheckResultHistoryItem)->getConnectionName();
        $tableName = EloquentHealthResultStore::getHistoryItemInstance()->getTable();

        if (Schema::connection($connection)->hasTable($tableName)) {
            return;
        }

        Schema::connection($connection)->create($tableName, function (Blueprint $table) {
            $table->id();
            $table->string('check_name');
            $table->string('check_label');
            $table->string('status');
            $table->text('notification_message')->nullable();
            $table->string('short_summary')->nullable();
            $table->json('meta');
            $table->timestamp('ended_at');
            $table->uuid('batch');
            $table->timestamps();

            $table->index('created_at');
            $table->index('batch');
        });
    }

    private function createIfMissing(string $tableName, Closure $callback): void
    {
        if (! Schema::hasTable($tableName)) {
            Schema::create($tableName, $callback);
        }
    }
};
