<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $legacyApproveId = DB::table('permissions')->where('slug', 'leave.approve')->value('id');
        if ($legacyApproveId !== null) {
            DB::table('role_permissions')->where('permission_id', (int) $legacyApproveId)->delete();
            DB::table('permissions')->where('id', (int) $legacyApproveId)->delete();
        }

        $newIds = DB::table('permissions')
            ->whereIn('slug', ['leave.approve.manager', 'leave.approve.hr'])
            ->pluck('id')
            ->map(fn ($id): int => (int) $id)
            ->all();

        if ($newIds === []) {
            return;
        }

        $ownerRoleIds = DB::table('roles')->where('slug', 'owner')->pluck('id')->map(fn ($id): int => (int) $id)->all();
        $now = now();

        foreach ($ownerRoleIds as $roleId) {
            foreach ($newIds as $permissionId) {
                $exists = DB::table('role_permissions')
                    ->where('role_id', $roleId)
                    ->where('permission_id', $permissionId)
                    ->exists();

                if ($exists) {
                    continue;
                }

                DB::table('role_permissions')->insert([
                    'role_id' => $roleId,
                    'permission_id' => $permissionId,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }
    }

    public function down(): void
    {
        // Intentionally non-destructive: re-adding legacy permissions could break RBAC assumptions.
    }
};
