<?php

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

use App\Models\AdminUser;
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\AdminUserApiPresenter;

/** DELETE /api/v1/admin/admin-users/{admin_user} */
final class AdminUserDestroyController extends Controller
{
    public function __invoke(Request $request, AdminUser $admin_user): JsonResponse
    {
        /** @var AdminUser $actor */
        $actor = $request->lotteryAdmin();
        AdminAccountScopeGuard::assertPlatformAccount($admin_user);

        if ((int) $actor->getKey() === (int) $admin_user->getKey()) {
            return ApiMessage::errorResponse($request, 'admin.user_cannot_delete_self', ErrorCode::ValidationFailed->value, null, 422);
        }

        if ($admin_user->isSuperAdmin()) {
            $hasOther = AdminUser::query()
                ->whereKeyNot($admin_user->getKey())
                ->where('is_super_admin', true)
                ->exists();
            if (! $hasOther) {
                return ApiMessage::errorResponse($request, 'admin.user_cannot_delete_last_super_admin', ErrorCode::ValidationFailed->value, null, 422);
            }
        }

        $before = AdminUserApiPresenter::listItem($admin_user);
        $id = (int) $admin_user->id;
        $admin_user->delete();

        AuditLogger::recordForAdmin(
            $actor,
            $request,
            'system',
            'admin_user.delete',
            'admin_user',
            (string) $id,
            $before,
            null,
        );

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