<?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/player-win-loss */
final class AdminReportPlayerWinLossController 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);
        $playerId = isset($validated['player_id']) ? (int) $validated['player_id'] : null;
        $scope = AdminScopePolicy::resolveContext($request, $admin, 'site_code', 'agent_node_id');

        $paginator = $service->playerWinLossPaginated(
            $playerId,
            $range['date_from'],
            $range['date_to'],
            $p['page'],
            $p['perPage'],
            $scope,
        );

        return AdminApiList::jsonWith($paginator, static function (object $row): array {
            return [
                'player_id' => (int) $row->player_id,
                'agent_node_id' => isset($row->agent_node_id) ? (int) $row->agent_node_id : null,
                'agent_code' => isset($row->agent_code) ? (string) $row->agent_code : null,
                'agent_name' => isset($row->agent_name) ? (string) $row->agent_name : null,
                'username' => $row->username !== null ? (string) $row->username : 'player#'.(int) $row->player_id,
                'total_bet_minor' => (int) $row->total_bet_minor,
                'total_payout_minor' => (int) $row->total_payout_minor,
                'net_win_loss_minor' => (int) $row->net_win_loss_minor,
            ];
        }, [
            'currency_code' => $service->resolvePeriodCurrencyCode($range['date_from'], $range['date_to'], $scope),
        ]);
    }
}
