<?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
{
    public function up(): void
    {
        Schema::create('serp_operation_states', function (Blueprint $t) {
            $t->unsignedTinyInteger('id')->primary();
            $t->string('emergency_reason_code', 64)->nullable();
            $t->timestamp('emergency_stopped_at')->nullable()->index();
            $t->foreignId('emergency_actor_id')->nullable()->constrained('users')->nullOnDelete();
            $t->timestamp('last_health_at')->nullable();
            $t->bigInteger('last_balance_micros')->nullable();
            $t->unsignedInteger('last_provider_status_code')->nullable();
            $t->timestamp('last_provider_success_at')->nullable();
            $t->string('last_error_category', 64)->nullable();
            $t->timestamps();
        });
        DB::table('serp_operation_states')->insert(['id' => 1, 'created_at' => now(), 'updated_at' => now()]);
        Schema::create('serp_budget_entries', function (Blueprint $t) {
            $t->id();
            $t->string('reservation_key', 191)->unique();
            $t->foreignId('serp_check_id')->nullable()->constrained()->restrictOnDelete();
            $t->string('mode', 16);
            $t->unsignedBigInteger('reserved_micros');
            $t->unsignedBigInteger('actual_micros')->nullable();
            $t->char('currency', 3)->default('USD');
            $t->string('provider_task_id', 191)->nullable()->unique();
            $t->timestamp('reserved_at')->index();
            $t->timestamp('reconciled_at')->nullable();
            $t->timestamps();
            $t->index(['mode', 'reserved_at']);
        });
        Schema::create('serp_operation_audits', function (Blueprint $t) {
            $t->id();
            $t->foreignId('actor_user_id')->nullable()->constrained('users')->nullOnDelete();
            $t->string('action', 96)->index();
            $t->uuid('correlation_id')->index();
            $t->json('context')->nullable();
            $t->timestamps();
        });
        Schema::table('serp_checks', function (Blueprint $t) {
            $t->timestamp('provider_next_poll_at')->nullable()->after('provider_last_polled_at')->index();
        });
        $now = now();
        foreach ([['serp_operations.view', 'SERP operasyonlarını görüntüleme'], ['serp_operations.manage', 'SERP operasyonlarını yönetme'], ['serp_operations.emergency_stop', 'SERP acil durdurma yönetimi']] as [$name,$label]) {
            DB::table('permissions')->updateOrInsert(['name' => $name], ['label' => $label, 'created_at' => $now, 'updated_at' => $now]);
        }$roles = DB::table('roles')->pluck('id', 'name');
        $perms = DB::table('permissions')->pluck('id', 'name');
        foreach (['support', 'admin', 'super_admin'] as $role) {
            if (! isset($roles[$role])) {
                continue;
            }
            DB::table('permission_role')->updateOrInsert(['role_id' => $roles[$role], 'permission_id' => $perms['serp_operations.view']], ['created_at' => $now, 'updated_at' => $now]);
        }foreach (['serp_operations.manage', 'serp_operations.emergency_stop'] as $name) {
            if (! isset($roles['super_admin'])) {
                continue;
            }
            DB::table('permission_role')->updateOrInsert(['role_id' => $roles['super_admin'], 'permission_id' => $perms[$name]], ['created_at' => $now, 'updated_at' => $now]);
        }
    }

    public function down(): void
    {
        Schema::table('serp_checks', fn (Blueprint $t) => $t->dropColumn('provider_next_poll_at'));
        Schema::dropIfExists('serp_operation_audits');
        Schema::dropIfExists('serp_budget_entries');
        Schema::dropIfExists('serp_operation_states');
        DB::table('permissions')->whereIn('name', ['serp_operations.view', 'serp_operations.manage', 'serp_operations.emergency_stop'])->delete();
    }
};
