<?php

namespace App\Http\Controllers\Api\V1\Admin\User;

use App\Models\AdminRole;
use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Support\AdminPermissionInheritance;
use App\Lottery\ErrorCode;
use App\Support\AdminAccountScopeGuard;
use App\Support\AdminRoleApiPresenter;
use App\Support\ApiMessage;
use App\Support\PlatformSystemRoles;
use App\Http\Requests\Admin\AdminRolePermissionSyncRequest;

final class AdminRolePermissionSyncController extends Controller
{
    public function __invoke(AdminRolePermissionSyncRequest $request, AdminRole $admin_role): JsonResponse
    {
        AdminAccountScopeGuard::assertSystemRole($admin_role);

        if ($admin_role->slug === PlatformSystemRoles::SLUG_SUPER_ADMIN) {
            return ApiMessage::errorResponse(
                $request,
                'admin.role_super_admin_permissions_fixed',
                ErrorCode::ValidationFailed->value,
                null,
                422,
            );
        }

        $slugs = AdminPermissionInheritance::expand(
            array_values(array_unique($request->validated('permission_slugs', []))),
        );
        $before = AdminRoleApiPresenter::item($admin_role);

        DB::transaction(function () use ($admin_role, $slugs): void {
            $admin_role->syncLegacyPermissionSlugs($slugs);
        });
        $admin_role->refresh();

        AuditLogger::recordForAdmin(
            $request->lotteryAdmin(),
            $request,
            'system',
            'admin_role.sync_permissions',
            'admin_role',
            (string) $admin_role->id,
            $before,
            AdminRoleApiPresenter::item($admin_role),
        );

        return ApiResponse::success(AdminRoleApiPresenter::item($admin_role));
    }
}
