<?php

declare(strict_types=1);

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

/**
 * Widen users.two_factor_secret from VARCHAR(255) to TEXT so that Laravel's
 * encrypt() payload (base64 JSON of iv+value+mac+tag, ~280+ chars) fits.
 *
 * Bug #8 fix for fresh installs against the original create_users_table
 * migration (which was patched in the same release to use text(), but
 * existing 1.0.0 installs still carry VARCHAR(255)). This ALTER is
 * idempotent — skipped if the column is already TEXT.
 *
 * @see _qa-audit/DEMO01_VERIFICATION.md Bug 8
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('users') || ! Schema::hasColumn('users', 'two_factor_secret')) {
            return;
        }

        $col = collect(DB::select(
            "SHOW COLUMNS FROM users WHERE Field = 'two_factor_secret'"
        ))->first();
        if (! $col) {
            return;
        }

        $type = strtolower((string) $col->Type);
        if (str_contains($type, 'text')) {
            return; // already widened
        }

        DB::statement('ALTER TABLE users MODIFY two_factor_secret TEXT NULL');
    }

    public function down(): void
    {
        // Narrowing could truncate encrypted secrets — intentional no-op.
    }
};
