<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('leads', function (Blueprint $table) {
            $table->timestamp('reopened_at')->nullable()->after('completed_at');
            $table->unsignedInteger('reopen_count')->default(0)->after('reopened_at');
        });
        Schema::create('lead_reopen_histories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('business_id')->index();
            $table->foreignId('lead_id')->index();
            $table->foreignId('from_stage_id')->index();
            $table->foreignId('to_stage_id')->index();
            $table->foreignId('reopened_by')->nullable()->index();
            $table->text('reason');
            $table->timestamps();
        });
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        Permission::firstOrCreate(['name' => 'reopen_completed_leads', 'guard_name' => 'web']);
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function down(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        Permission::where('name', 'reopen_completed_leads')->where('guard_name', 'web')->delete();
        Schema::dropIfExists('lead_reopen_histories');
        Schema::table('leads', fn (Blueprint $table) => $table->dropColumn(['reopened_at', 'reopen_count']));
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
