<?php

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

use App\Http\Controllers\Controller;
use App\Http\Middleware\RecordAdminApiAudit;
use App\Http\Requests\Admin\AdminSettlementPeriodStoreRequest;
use App\Services\AuditLogger;
use App\Services\AgentSettlement\AgentSettlementPeriodOpenService;
use App\Support\AdminAgentSettlementScope;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

final class AgentSettlementPeriodStoreController extends Controller
{
    public function __invoke(
        AdminSettlementPeriodStoreRequest $request,
        AgentSettlementPeriodOpenService $openService,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $data = $request->validated();
        abort_if(
            ! AdminAgentSettlementScope::siteAccessible($admin, (int) $data['admin_site_id']),
            404,
        );
        AdminAgentSettlementScope::assertCanManageSitePeriods($admin);

        $row = $openService->open($data);
        $id = (int) $row->id;

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'settlement',
            actionCode: 'settlement_period.store',
            targetType: 'settlement_period',
            targetId: (string) $id,
            beforeJson: null,
            afterJson: (array) $row,
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

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