<?php

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

use Illuminate\Http\Request;
use App\Support\AdminApiList;
use Illuminate\Http\JsonResponse;
use App\Models\JackpotContribution;
use App\Http\Controllers\Controller;
use App\Support\AdminScopePolicy;

/**
 * GET /api/v1/admin/jackpot/contributions — Jackpot 蓄水流水。
 */
final class AdminJackpotContributionIndexController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);
        $scope = AdminScopePolicy::resolveContext($request, $admin);

        $p = AdminApiList::readPaging($request);
        $drawNo = trim((string) $request->query('draw_no', ''));

        $q = JackpotContribution::query()
            ->with(['draw:id,draw_no', 'pool:id,currency_code', 'player:id,site_code,username,nickname,site_player_id', 'ticketItem:id,ticket_no'])
            ->orderByDesc('id');

        if ($drawNo !== '') {
            $q->whereHas('draw', fn ($d) => $d->where('draw_no', 'like', '%'.$drawNo.'%'));
        }

        AdminScopePolicy::applyViaPlayer($q, $scope);

        $paginator = $q->paginate($p['perPage'], ['*'], 'page', $p['page']);

        return AdminApiList::json($paginator, fn (JackpotContribution $r) => [
            'id' => (int) $r->id,
            'draw_id' => (int) $r->draw_id,
            'draw_no' => $r->draw?->draw_no,
            'jackpot_pool_id' => (int) $r->jackpot_pool_id,
            'currency_code' => $r->pool?->currency_code,
            'player_id' => (int) $r->player_id,
            'site_code' => $r->player?->site_code,
            'site_player_id' => $r->player?->site_player_id,
            'username' => $r->player?->username,
            'nickname' => $r->player?->nickname,
            'ticket_item_id' => $r->ticket_item_id !== null ? (int) $r->ticket_item_id : null,
            'ticket_no' => $r->ticketItem?->ticket_no,
            'contribution_amount' => (int) $r->contribution_amount,
            'created_at' => $r->created_at?->toIso8601String(),
        ]);
    }
}
