<?php

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

use App\Http\Controllers\Controller;
use App\Http\Middleware\RecordAdminApiAudit;
use App\Http\Requests\Admin\AdminAgentLineStoreRequest;
use App\Services\Agent\AgentSiteProvisioningService;
use App\Services\AuditLogger;
use App\Support\AdminIntegrationSitePresenter;
use App\Support\AgentLinePresenter;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

/** POST /api/v1/admin/agent-lines */
final class AgentLineStoreController extends Controller
{
    public function __invoke(
        AdminAgentLineStoreRequest $request,
        AgentSiteProvisioningService $service,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $result = $service->createRootAgent($admin, $request->validated());
        $site = $result['site'];
        $node = $result['agent_node'];

        $payload = AgentLinePresenter::provisioned($site, $node);

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'agent',
            actionCode: 'agent_line.provision',
            targetType: 'admin_site',
            targetId: (string) $site->id,
            afterJson: [
                'site' => AdminIntegrationSitePresenter::detail($site),
                'agent_node_id' => (int) $node->id,
            ],
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

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