<?php

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

use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\PaginationTrait;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminAgentSettlementScope;
use App\Services\AgentSettlement\SettlementOperationsListFilters;
use App\Services\AgentSettlement\SettlementOperationsListService;

/** GET /api/v1/admin/settlement-operations */
final class AgentSettlementOperationsIndexController extends Controller
{
    use PaginationTrait;

    public function __construct(
        private readonly SettlementOperationsListService $operationsList,
    ) {}

    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $filters = SettlementOperationsListFilters::fromQuery($request->query());

        if ($filters->settlementPeriodId !== null) {
            abort_if(! AdminAgentSettlementScope::periodAccessible($admin, $filters->settlementPeriodId), 403);
        }

        if ($filters->adminSiteId !== null) {
            abort_if(! AdminAgentSettlementScope::siteAccessible($admin, $filters->adminSiteId), 403);
        }

        $page = $this->page($request);
        $perPage = $this->perPage($request, 'per_page', 20, 100);

        $result = $this->operationsList->list($admin, $page, $perPage, $filters);
        $total = (int) $result['total'];
        $lastPage = max(1, (int) ceil($total / max(1, $perPage)));

        return ApiResponse::success([
            'items' => $result['items'],
            'total' => $total,
            'page' => $page,
            'per_page' => $perPage,
            'last_page' => $lastPage,
        ]);
    }
}
