<?php

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

use App\Models\AdminUser;
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\AdminUserApiPresenter;
use App\Support\AdminPlatformUserSiteGuard;
use App\Http\Requests\Admin\AdminUserStoreRequest;

/**
 * 管理员用户创建。
 *
 * POST /api/v1/admin/admin-users
 */
final class AdminUserStoreController extends Controller
{
    public function __invoke(AdminUserStoreRequest $request): JsonResponse
    {
        /** @var AdminUser $actor */
        $actor = $request->lotteryAdmin();

        $email = is_string($request->validated('email'))
            ? trim($request->validated('email'))
            : null;

        $roleSlugs = array_values(array_unique($request->validated('role_slugs')));
        $siteId = (int) $request->validated('admin_site_id');
        AdminPlatformUserSiteGuard::assertActorCanAssignSite($actor, $siteId);

        $user = DB::transaction(function () use ($request, $email, $roleSlugs, $siteId): AdminUser {
            $created = AdminUser::query()->create([
                'username' => $request->validated('username'),
                'name' => $request->validated('nickname'),
                'email' => $email,
                'password' => $request->validated('password'),
                'status' => $request->validated('status', 0),
            ]);
            $created->syncSystemRoleSlugsForSite($siteId, $roleSlugs);

            return $created;
        });

        $user->load('roles');

        AuditLogger::recordForAdmin(
            $actor,
            $request,
            'system',
            'admin_user.create',
            'admin_user',
            (string) $user->getKey(),
            null,
            AdminUserApiPresenter::listItem($user),
        );

        return ApiResponse::success(AdminUserApiPresenter::listItem($user));
    }
}
