<?php

namespace App\Http\Controllers\Api\V1\Ticket;

use App\Models\Draw;
use App\Models\Player;
use App\Models\TicketItem;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Models\TicketCombination;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Draw\DrawResultViewService;

/**
 * `GET /api/v1/ticket/draws/{draw_no}/my-match` — 当期本人号码与已发布开奖 23 格的交集（用于开奖页高亮）。
 */
final class TicketDrawMyMatchController extends Controller
{
    public function __construct(
        private readonly DrawResultViewService $drawResultView,
    ) {}

    public function __invoke(Request $request, string $draw_no): JsonResponse
    {
        /** @var Player $player */
        $player = $request->attributes->get('lottery_player');
        $draw_no = trim($draw_no);

        $draw = Draw::query()->where('draw_no', $draw_no)->first();
        if ($draw === null || ! in_array($draw->status, DrawResultViewService::publishedDrawStatuses(), true)) {
            return ApiResponse::success([
                'draw_no' => $draw_no,
                'hit_numbers_4d' => [],
                'total_win_minor' => 0,
                'total_jackpot_win_minor' => 0,
                'winning_ticket_count' => 0,
                'has_bets' => false,
            ]);
        }

        $payload = $this->drawResultView->summarizeDraw($draw);
        if ($payload === null) {
            return ApiResponse::success([
                'draw_no' => $draw_no,
                'hit_numbers_4d' => [],
                'total_win_minor' => 0,
                'total_jackpot_win_minor' => 0,
                'winning_ticket_count' => 0,
                'has_bets' => false,
            ]);
        }

        $board = collect($payload['result_items'] ?? [])
            ->pluck('number_4d')
            ->filter()
            ->map(fn ($n) => self::norm4d((string) $n))
            ->unique()
            ->flip();

        $itemIds = TicketItem::query()
            ->where('draw_id', $draw->id)
            ->where('player_id', $player->id)
            ->whereIn('status', ['pending_draw', 'pending_payout', 'settled_win', 'settled_lose'])
            ->pluck('id');

        $hasBets = $itemIds->isNotEmpty();
        $winningItemIds = TicketItem::query()
            ->where('draw_id', $draw->id)
            ->where('player_id', $player->id)
            ->whereIn('status', ['settled_win', 'pending_payout'])
            ->where(function ($q): void {
                $q->where('win_amount', '>', 0)
                    ->orWhere('jackpot_win_amount', '>', 0);
            })
            ->pluck('id');

        $hits = [];
        if ($winningItemIds->isNotEmpty()) {
            $hits = TicketCombination::query()
                ->whereIn('ticket_item_id', $winningItemIds)
                ->pluck('number_4d')
                ->map(fn ($n) => self::norm4d((string) $n))
                ->filter(fn (string $n) => isset($board[$n]))
                ->unique()
                ->values()
                ->all();
        }

        $sums = TicketItem::query()
            ->where('draw_id', $draw->id)
            ->where('player_id', $player->id)
            ->whereIn('status', ['settled_win', 'settled_lose', 'pending_payout'])
            ->selectRaw('coalesce(sum(win_amount),0) as sum_win, coalesce(sum(jackpot_win_amount),0) as sum_jackpot')
            ->first();

        return ApiResponse::success([
            'draw_no' => $draw_no,
            'hit_numbers_4d' => $hits,
            'total_win_minor' => (int) ($sums->sum_win ?? 0),
            'total_jackpot_win_minor' => (int) ($sums->sum_jackpot ?? 0),
            'winning_ticket_count' => $winningItemIds->count(),
            'has_bets' => $hasBets,
        ]);
    }

    private static function norm4d(string $n): string
    {
        $n = preg_replace('/\D/', '', $n) ?? '';

        return str_pad(substr($n, -4), 4, '0', STR_PAD_LEFT);
    }
}
