<?php

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

return new class extends Migration
{
    /**
     * Replaces the boolean `is_approved` flag with a proper `status` enum so
     * the admin can distinguish "never reviewed yet" (pending) from
     * "reviewed and rejected" — a boolean can't tell those apart, which is
     * exactly what the admin review-moderation screen needs.
     */
    public function up(): void
    {
        if (! Schema::hasColumn('reviews', 'status')) {
            Schema::table('reviews', function (Blueprint $table) {
                $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending')->after('comment');
            });
        }

        if (Schema::hasColumn('reviews', 'is_approved')) {
            DB::table('reviews')->where('is_approved', true)->update(['status' => 'approved']);
            DB::table('reviews')->where('is_approved', false)->update(['status' => 'pending']);

            Schema::table('reviews', function (Blueprint $table) {
                $table->dropColumn('is_approved');
            });
        }

        if (! Schema::hasIndex('reviews', 'reviews_status_index')) {
            Schema::table('reviews', function (Blueprint $table) {
                $table->index('status');
            });
        }
    }

    public function down(): void
    {
        if (! Schema::hasColumn('reviews', 'is_approved')) {
            Schema::table('reviews', function (Blueprint $table) {
                $table->boolean('is_approved')->default(false)->after('comment');
            });

            DB::table('reviews')->where('status', 'approved')->update(['is_approved' => true]);
        }

        if (Schema::hasColumn('reviews', 'status')) {
            Schema::table('reviews', function (Blueprint $table) {
                if (Schema::hasIndex('reviews', 'reviews_status_index')) {
                    $table->dropIndex('reviews_status_index');
                }

                $table->dropColumn('status');
            });
        }
    }
};
