<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('fast_events_treasure', function (Blueprint $table) {
            // Add status column if it doesn't exist
            if (!Schema::hasColumn('fast_events_treasure', 'status')) {
                $table->enum('status', ['pending', 'approved', 'rejected', 'collected'])
                      ->default('pending')
                      ->after('total_points');
            }

            // Add rejection_reason column if it doesn't exist
            if (!Schema::hasColumn('fast_events_treasure', 'rejection_reason')) {
                $table->text('rejection_reason')->nullable()->after('accepted_at');
            }

            // Add reviewed_at column if it doesn't exist
            if (!Schema::hasColumn('fast_events_treasure', 'reviewed_at')) {
                $table->timestamp('reviewed_at')->nullable()->after('rejection_reason');
            }
        });

        // Update existing records to set status based on current fields
        DB::statement("
            UPDATE fast_events_treasure
            SET status = CASE
                WHEN collected = 1 THEN 'collected'
                WHEN accepted = 1 THEN 'approved'
                WHEN accepted = 0 THEN 'pending'
                ELSE 'pending'
            END
            WHERE status IS NULL OR status = ''
        ");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('fast_events_treasure', function (Blueprint $table) {
            $table->dropColumn(['status', 'rejection_reason', 'reviewed_at']);
        });
    }
};
