<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AdminReportQueryRequest;
use App\Services\Admin\AdminReportQueryService;
use App\Support\AdminApiList;
use App\Support\AdminScopePolicy;
use Illuminate\Http\JsonResponse;

/** GET /api/v1/admin/reports/provider-profit */
final class AdminReportProviderProfitController extends Controller
{
    public function __invoke(AdminReportQueryRequest $request, AdminReportQueryService $service): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $validated = $request->validated();
        $paging = AdminApiList::readPaging($request);
        $range = $service->resolveDateRange($validated);
        $scope = AdminScopePolicy::resolveContext($request, $admin, 'site_code', 'agent_node_id');
        $paginator = $service->providerProfitPaginated(
            $range['date_from'], $range['date_to'], $paging['page'], $paging['perPage'], $scope,
        );

        return AdminApiList::jsonWith($paginator, static function (object $row): array {
            return [
                'provider_code' => (string) $row->provider_code,
                'provider_name' => (string) $row->provider_name,
                'ticket_item_count' => (int) $row->ticket_item_count,
                'total_bet_minor' => (int) $row->total_bet_minor,
                'total_payout_minor' => (int) $row->total_payout_minor,
                'approx_house_gross_minor' => (int) $row->approx_house_gross_minor,
            ];
        }, [
            'currency_code' => $service->resolvePeriodCurrencyCode($range['date_from'], $range['date_to'], $scope),
        ]);
    }
}
