<?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/play-dimension */
final class AdminReportPlayDimensionController extends Controller
{
    public function __invoke(AdminReportQueryRequest $request, AdminReportQueryService $service): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $validated = $request->validated();
        $p = AdminApiList::readPaging($request);
        $range = $service->resolveDateRange($validated);
        $playCode = isset($validated['play_code']) ? trim((string) $validated['play_code']) : null;
        $scope = AdminScopePolicy::resolveContext($request, $admin, 'site_code', 'agent_node_id');

        $paginator = $service->playDimensionPaginated(
            $playCode !== '' ? $playCode : null,
            $range['date_from'],
            $range['date_to'],
            $p['page'],
            $p['perPage'],
            $scope,
        );

        return AdminApiList::jsonWith($paginator, static function (object $row): array {
            return [
                'play_code' => (string) $row->play_code,
                'dimension' => (int) $row->dimension,
                '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),
        ]);
    }
}
