<?php

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

use App\Models\Player;
use App\Lottery\ErrorCode;
use App\Models\SettlementBatch;
use App\Models\TicketItem;
use App\Models\TicketOrder;
use App\Models\WalletTxn;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Draw\DrawResultViewService;

/**
 * `GET /api/v1/ticket/items/{ticket_no}` — 注单详情（单注项 + 组合 + 结算摘要）。
 */
final class TicketItemShowController extends Controller
{
    public function __construct(
        private readonly DrawResultViewService $drawResultView,
    ) {}

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

        $item = TicketItem::query()
            ->where('ticket_no', $ticket_no)
            ->where('player_id', $player->id)
            ->with([
                'combinations',
                'draw',
                'order',
                'latestSettlementDetail',
            ])
            ->first();

        if ($item === null) {
            return ApiResponse::error(
                trans('api.not_found', [], $request->lotteryLocale()),
                ErrorCode::NotFound->value,
                null,
                404,
            );
        }

        $draw = $item->draw;
        $published = $draw !== null && in_array($draw->status, DrawResultViewService::publishedDrawStatuses(), true);
        $drawPayload = $published && $draw !== null ? $this->drawResultView->summarizeDraw($draw) : null;

        $detail = $item->latestSettlementDetail;
        $settlementBatch = $detail?->batch;
        $order = $item->order;
        $betTxn = WalletTxn::query()
            ->where('player_id', $player->id)
            ->where('biz_type', 'bet_deduct')
            ->where('biz_no', $order?->order_no)
            ->orderByDesc('id')
            ->first();
        $payoutTxn = $settlementBatch !== null
            ? WalletTxn::query()
                ->where('player_id', $player->id)
                ->where('biz_type', 'settle_payout')
                ->where('biz_no', 'SB'.$settlementBatch->id)
                ->first()
            : null;

        $timeline = [];
        if ($order?->created_at !== null) {
            $timeline[] = [
                'code' => 'placed',
                'label' => '已下注',
                'time' => $order->created_at->toIso8601String(),
            ];
        }
        if ($betTxn?->created_at !== null) {
            $timeline[] = [
                'code' => 'deducted',
                'label' => '已扣款',
                'time' => $betTxn->created_at->toIso8601String(),
            ];
        }
        if ($drawPayload !== null && $draw?->current_result_version !== null) {
            $timeline[] = [
                'code' => 'draw_published',
                'label' => '开奖结果已发布',
                'time' => $draw->draw_time?->toIso8601String() ?? $draw->updated_at?->toIso8601String(),
            ];
        }
        if ($settlementBatch?->started_at !== null) {
            $timeline[] = [
                'code' => 'settlement_started',
                'label' => '结算开始',
                'time' => $settlementBatch->started_at->toIso8601String(),
            ];
        }
        if ($item->settled_at !== null) {
            $timeline[] = [
                'code' => 'settled',
                'label' => $item->status === 'settled_win' ? '已派彩' : '已结算',
                'time' => $item->settled_at->toIso8601String(),
            ];
        } elseif ($payoutTxn?->created_at !== null) {
            $timeline[] = [
                'code' => 'settled',
                'label' => '已派彩',
                'time' => $payoutTxn->created_at->toIso8601String(),
            ];
        }

        $matchDetail = $detail?->match_detail_json;
        $matchedLines = [];
        if (is_array($matchDetail['lines'] ?? null)) {
            foreach ($matchDetail['lines'] as $line) {
                if (! is_array($line)) {
                    continue;
                }
                $matchedLines[] = [
                    'number_4d' => isset($line['number_4d']) ? (string) $line['number_4d'] : null,
                    'matched_tier' => isset($line['matched_tier']) ? (string) $line['matched_tier'] : null,
                    'bet_amount' => isset($line['bet_amount']) ? (int) $line['bet_amount'] : null,
                    'odds_value' => isset($line['odds_value']) ? (int) $line['odds_value'] : null,
                    'payout' => isset($line['payout']) ? (int) $line['payout'] : null,
                ];
            }
        }

        $matchResult = [
            'matched' => $detail !== null && ((int) $detail->win_amount > 0 || (int) $detail->jackpot_allocation_amount > 0),
            'matched_prize_tier' => $detail?->matched_prize_tier,
            'win_amount_minor' => $detail !== null ? (int) $detail->win_amount : 0,
            'jackpot_allocation_minor' => $detail !== null ? (int) $detail->jackpot_allocation_amount : 0,
            'match_detail' => $matchDetail,
            'lines' => $matchedLines,
        ];

        return ApiResponse::success([
            'ticket_no' => $item->ticket_no,
            'order_no' => $item->order?->order_no,
            'order_status' => $item->order?->status,
            'draw_no' => $draw?->draw_no,
            'currency_code' => $item->order?->currency_code,
            'play_code' => $item->play_code,
            'dimension' => $item->dimension,
            'digit_slot' => $item->digit_slot,
            'original_number' => $item->original_number,
            'normalized_number' => $item->normalized_number,
            'unit_bet_amount' => (int) $item->unit_bet_amount,
            'total_bet_amount' => (int) $item->total_bet_amount,
            'rebate_rate_snapshot' => (string) $item->rebate_rate_snapshot,
            'actual_deduct_amount' => (int) $item->actual_deduct_amount,
            'status' => $item->status,
            'fail_reason_code' => $item->fail_reason_code,
            'fail_reason_text' => $item->fail_reason_text,
            'win_amount' => (int) $item->win_amount,
            'jackpot_win_amount' => (int) $item->jackpot_win_amount,
            'settled_at' => $item->settled_at?->toIso8601String(),
            'placed_at' => $item->order?->created_at?->toIso8601String(),
            'odds_snapshot_json' => $item->odds_snapshot_json,
            'combinations' => $item->combinations->map(fn ($c) => [
                'combination_no' => (int) $c->combination_no,
                'number_4d' => (string) $c->number_4d,
                'bet_amount' => (int) $c->bet_amount,
                'estimated_payout' => (int) $c->estimated_payout,
            ])->values()->all(),
            'settlement' => $detail === null ? null : [
                'matched_prize_tier' => $detail->matched_prize_tier,
                'win_amount_minor' => (int) $detail->win_amount,
                'jackpot_allocation_minor' => (int) $detail->jackpot_allocation_amount,
            ],
            'match_result' => $matchResult,
            'timeline' => $timeline,
            'published_draw_results' => $drawPayload,
        ]);
    }
}
