<?php

use App\Models\AdminsTask;
use App\Models\AdminsTaskStatus;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add the status_id column
        Schema::table('admins_tasks', function (Blueprint $table) {
            $table->foreignId('status_id')->nullable()->after('status');
        });

        // Migrate existing status data
        $this->migrateStatusData();

        // Remove the old status column and add constraint
        Schema::table('admins_tasks', function (Blueprint $table) {
            $table->dropColumn('status');
            $table->foreign('status_id')->references('id')->on('admins_task_statuses')->onDelete('restrict');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Add back the status column
        Schema::table('admins_tasks', function (Blueprint $table) {
            $table->string('status')->default('pending')->after('end_date');
        });

        // Migrate data back
        $this->migrateStatusDataBack();

        // Remove the status_id column
        Schema::table('admins_tasks', function (Blueprint $table) {
            $table->dropForeign(['status_id']);
            $table->dropColumn('status_id');
        });
    }

    /**
     * Migrate status data from string to relationship
     */
    private function migrateStatusData(): void
    {
        $statusMapping = [
            'pending' => AdminsTaskStatus::where('key', 'pending')->first()?->id,
            'in_progress' => AdminsTaskStatus::where('key', 'in_progress')->first()?->id,
            'completed' => AdminsTaskStatus::where('key', 'completed')->first()?->id,
            'cancelled' => AdminsTaskStatus::where('key', 'cancelled')->first()?->id,
            'on_hold' => AdminsTaskStatus::where('key', 'on_hold')->first()?->id,
        ];

        foreach ($statusMapping as $oldStatus => $newStatusId) {
            if ($newStatusId) {
                AdminsTask::withoutGlobalScopes()
                    ->where('status', $oldStatus)
                    ->update(['status_id' => $newStatusId]);
            }
        }

        // Set default status for any tasks without a mapped status
        $defaultStatusId = AdminsTaskStatus::where('key', 'pending')->first()?->id;
        if ($defaultStatusId) {
            AdminsTask::withoutGlobalScopes()
                ->whereNull('status_id')
                ->update(['status_id' => $defaultStatusId]);
        }
    }

    /**
     * Migrate status data back from relationship to string
     */
    private function migrateStatusDataBack(): void
    {
        $statusMapping = [
            'pending' => AdminsTaskStatus::where('key', 'pending')->first()?->id,
            'in_progress' => AdminsTaskStatus::where('key', 'in_progress')->first()?->id,
            'completed' => AdminsTaskStatus::where('key', 'completed')->first()?->id,
            'cancelled' => AdminsTaskStatus::where('key', 'cancelled')->first()?->id,
            'on_hold' => AdminsTaskStatus::where('key', 'on_hold')->first()?->id,
        ];

        foreach ($statusMapping as $statusKey => $statusId) {
            if ($statusId) {
                AdminsTask::withoutGlobalScopes()
                    ->where('status_id', $statusId)
                    ->update(['status' => $statusKey]);
            }
        }

        // Set default status for any tasks without a mapped status
        AdminsTask::withoutGlobalScopes()
            ->whereNull('status')
            ->update(['status' => 'pending']);
    }
};
