<?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
    {
        foreach (['wo_works', 'wo_parts'] as $table) {
            Schema::table($table, function (Blueprint $t) use ($table) {
                if (! Schema::hasColumn($table, 'requires_approval')) {
                    $t->boolean('requires_approval')->default(false)->after('status');
                }
                if (! Schema::hasColumn($table, 'approved_at')) {
                    $t->timestamp('approved_at')->nullable()->after('requires_approval');
                }
                if (! Schema::hasColumn($table, 'approval_token')) {
                    $t->string('approval_token', 32)->nullable()->after('approved_at');
                }
                if (! Schema::hasColumn($table, 'declined_at')) {
                    $t->timestamp('declined_at')->nullable()->after('approval_token');
                }
            });
        }
        // Index for fast token lookup
        try {
            Schema::table('wo_works', fn (Blueprint $t) => $t->index('approval_token', 'wow_approval_token_idx'));
        } catch (\Throwable $e) {}
        try {
            Schema::table('wo_parts', fn (Blueprint $t) => $t->index('approval_token', 'wop_approval_token_idx'));
        } catch (\Throwable $e) {}
    }

    public function down(): void
    {
        foreach (['wo_works', 'wo_parts'] as $table) {
            Schema::table($table, function (Blueprint $t) use ($table) {
                foreach (['requires_approval', 'approved_at', 'approval_token', 'declined_at'] as $col) {
                    if (Schema::hasColumn($table, $col)) $t->dropColumn($col);
                }
            });
        }
    }
};
