<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    private string $permission = 'accounting.accounts.manage';

    public function up(): void
    {
        if (! Schema::hasTable('role_profiles')) {
            return;
        }

        DB::table('role_profiles')
            ->whereIn('base_role', [User::ROLE_TENANT_ADMIN, User::ROLE_MANAGER, User::ROLE_ACCOUNTANT])
            ->orderBy('id')
            ->get(['id', 'permissions'])
            ->each(function (object $profile): void {
                $permissions = json_decode((string) $profile->permissions, true);

                if (! is_array($permissions)) {
                    $permissions = [];
                }

                if (! in_array($this->permission, $permissions, true)) {
                    $permissions[] = $this->permission;
                }

                DB::table('role_profiles')->where('id', $profile->id)->update([
                    'permissions' => json_encode(array_values(array_unique($permissions))),
                    'updated_at' => now(),
                ]);
            });
    }

    public function down(): void
    {
        if (! Schema::hasTable('role_profiles')) {
            return;
        }

        DB::table('role_profiles')
            ->whereIn('base_role', [User::ROLE_TENANT_ADMIN, User::ROLE_MANAGER, User::ROLE_ACCOUNTANT])
            ->orderBy('id')
            ->get(['id', 'permissions'])
            ->each(function (object $profile): void {
                $permissions = json_decode((string) $profile->permissions, true);

                if (! is_array($permissions)) {
                    return;
                }

                DB::table('role_profiles')->where('id', $profile->id)->update([
                    'permissions' => json_encode(array_values(array_diff($permissions, [$this->permission]))),
                    'updated_at' => now(),
                ]);
            });
    }
};
