<?php

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

use App\Models\AdminRole;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminAccountScopeGuard;
use App\Support\AdminRoleApiPresenter;
use App\Support\PlatformSystemRoles;

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

        if (PlatformSystemRoles::isFixedSlug((string) $admin_role->slug)) {
            return ApiMessage::errorResponse($request, 'admin.role_builtin_cannot_delete', ErrorCode::ValidationFailed->value, null, 422);
        }
        if ((bool) $admin_role->is_system) {
            return ApiMessage::errorResponse($request, 'admin.role_builtin_cannot_delete', ErrorCode::ValidationFailed->value, null, 422);
        }
        if ($admin_role->assignedUserCount() > 0) {
            return ApiMessage::errorResponse($request, 'admin.role_has_users_cannot_delete', ErrorCode::ValidationFailed->value, null, 422);
        }

        $before = AdminRoleApiPresenter::item($admin_role);
        $id = (int) $admin_role->id;
        $admin_role->delete();

        AuditLogger::recordForAdmin(
            $request->lotteryAdmin(),
            $request,
            'system',
            'admin_role.delete',
            'admin_role',
            (string) $id,
            $before,
            null,
        );

        return ApiResponse::success(['deleted' => true, 'id' => $id]);
    }
}
