<?php

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

/**
 * Add 'pending' to kb_documents.status ENUM.
 *
 * Background: the "Add Website" form in Knowledge Base writes a row with
 * status='pending' immediately so the user sees their entry while the
 * scrape job runs in the background. But the original ENUM only had
 * ('uploading','extracting','chunking','embedding','ready','failed','paused')
 * — so MySQL strict mode rejected the INSERT with "Data truncated for
 * column 'status'", the row never persisted, and the user saw nothing.
 *
 * Fix: extend the ENUM with 'pending' at the front. Idempotent — if
 * the column already includes 'pending' (re-runs, fresh installs that
 * shipped with the patched seeder), we skip the ALTER.
 */
return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasTable('kb_documents')) {
            return;
        }

        $col = DB::selectOne("SHOW COLUMNS FROM kb_documents WHERE Field = 'status'");
        if (!$col) {
            return;
        }

        // Already includes 'pending' → no-op.
        if (str_contains((string) $col->Type, "'pending'")) {
            return;
        }

        // Extend the ENUM. We keep the existing default ('uploading') so
        // any code paths that rely on the default-on-insert behavior are
        // unaffected.
        DB::statement("
            ALTER TABLE `kb_documents`
            MODIFY COLUMN `status` ENUM(
                'pending','uploading','extracting','chunking','embedding',
                'ready','failed','paused'
            ) NOT NULL DEFAULT 'uploading'
        ");
    }

    public function down(): void
    {
        if (!Schema::hasTable('kb_documents')) {
            return;
        }

        // Reverse — but only if no rows currently use 'pending'. We
        // never want to drop a value out from under live data; better
        // to fail the down() than silently lose status info.
        $usedByRows = DB::table('kb_documents')->where('status', 'pending')->count();
        if ($usedByRows > 0) {
            // Promote them to 'uploading' (the closest valid pre-fix state)
            // before shrinking the ENUM so we don't error.
            DB::table('kb_documents')->where('status', 'pending')->update(['status' => 'uploading']);
        }

        DB::statement("
            ALTER TABLE `kb_documents`
            MODIFY COLUMN `status` ENUM(
                'uploading','extracting','chunking','embedding',
                'ready','failed','paused'
            ) NOT NULL DEFAULT 'uploading'
        ");
    }
};
