<?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 App\Http\Controllers\Controller;
use App\Support\AdminAccountScopeGuard;
use App\Support\AdminUserApiPresenter;
use App\Http\Requests\Admin\AdminUserUpdateRequest;

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

        $admin_user->load('roles');
        $before = AdminUserApiPresenter::listItem($admin_user);

        $data = $request->validated();

        $updates = [];
        if (array_key_exists('nickname', $data)) {
            $updates['name'] = $data['nickname'];
        }
        if (array_key_exists('email', $data)) {
            $updates['email'] = ($data['email'] !== null && trim((string) $data['email']) !== '')
                ? trim((string) $data['email'])
                : null;
        }
        if (array_key_exists('status', $data)) {
            $updates['status'] = (int) $data['status'];
        }
        if (array_key_exists('password', $data) && is_string($data['password']) && $data['password'] !== '') {
            $updates['password'] = $data['password'];
        }

        if ($updates === []) {
            return ApiResponse::success($before);
        }

        $admin_user->fill($updates);
        $admin_user->save();
        $admin_user->load('roles');

        $after = AdminUserApiPresenter::listItem($admin_user);

        AuditLogger::recordForAdmin(
            $actor,
            $request,
            'system',
            'admin_user.update',
            'admin_user',
            (string) $admin_user->getKey(),
            $before,
            $after,
        );

        return ApiResponse::success($after);
    }
}
