<?php

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

use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\AuditLogger;
use App\Services\Integration\IntegrationSiteService;
use App\Support\AdminIntegrationSitePresenter;
use App\Http\Requests\Admin\AdminIntegrationSiteStoreRequest;
use App\Http\Middleware\RecordAdminApiAudit;

final class AdminIntegrationSiteStoreController extends Controller
{
    public function __invoke(
        AdminIntegrationSiteStoreRequest $request,
        IntegrationSiteService $service,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $result = $service->create($request->validated());
        $site = $result['site'];

        $payload = AdminIntegrationSitePresenter::withPlainSecretsOnce(
            AdminIntegrationSitePresenter::detail($site),
            $result['secrets'],
        );
        $payload['admin_user'] = [
            'id' => (int) $result['admin_user']->id,
            'username' => (string) $result['admin_user']->username,
            'nickname' => (string) $result['admin_user']->name,
            'email' => $result['admin_user']->email,
        ];

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'integration',
            actionCode: 'create',
            targetType: 'admin_site',
            targetId: (string) $site->id,
            afterJson: AdminIntegrationSitePresenter::detail($site),
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

        return ApiResponse::success($payload)->setStatusCode(201);
    }
}
