<?php

namespace App\Services\AgentSettlement;

use App\Support\AgentSettlementPeriodWindow;
use Illuminate\Support\Facades\DB;

final class UnsettledTicketPeriodWarning
{
    /**
     * 未结算注单：优先按游戏结算落账时间（settled_at）归属账期；未开奖仍按下注时间（created_at）。
     *
     * @return array{count: int, ticket_item_ids: list<int>}
     */
    public function countForSite(int $adminSiteId, string $periodStart, string $periodEnd): array
    {
        $siteCode = (string) DB::table('admin_sites')->where('id', $adminSiteId)->value('code');
        [$start, $end] = AgentSettlementPeriodWindow::boundStrings($periodStart, $periodEnd);

        $rows = DB::table('ticket_items as ti')
            ->join('players as p', 'p.id', '=', 'ti.player_id')
            ->where('p.site_code', $siteCode)
            ->whereIn('ti.status', ['pending_draw', 'pending_confirm', 'pending_payout'])
            ->whereNull('ti.agent_settled_at')
            ->where(function ($query) use ($start, $end): void {
                $query->where(function ($settled) use ($start, $end): void {
                    $settled->whereNotNull('ti.settled_at')
                        ->whereBetween('ti.settled_at', [$start, $end]);
                })->orWhere(function ($pending) use ($start, $end): void {
                    $pending->whereNull('ti.settled_at')
                        ->whereBetween('ti.created_at', [$start, $end]);
                });
            })
            ->pluck('ti.id')
            ->map(fn ($id): int => (int) $id)
            ->all();

        return [
            'count' => count($rows),
            'ticket_item_ids' => array_slice($rows, 0, 20),
        ];
    }
}
