<?php

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

use App\Http\Controllers\Controller;
use App\Services\AgentSettlement\AgentSettlementPeriodSummaryService;
use App\Support\AdminAgentSettlementScope;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

final class AgentSettlementPeriodIndexController extends Controller
{
    public function __invoke(
        Request $request,
        AgentSettlementPeriodSummaryService $summaryService,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $query = DB::table('settlement_periods')->orderByDesc('id');
        AdminAgentSettlementScope::applyToPeriodsQuery($query, $admin);

        $siteId = (int) $request->query('admin_site_id', 0);
        if ($siteId > 0) {
            $query->where('admin_site_id', $siteId);
        }

        $periods = $query->limit(100)->get();

        return ApiResponse::success([
            'items' => $summaryService->attachToPeriodRows($periods, $admin),
        ]);
    }
}
