<?php

namespace App\Services\Admin;

use App\Models\AdminUser;
use App\Models\Player;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

/** 站点客服仪表盘：玩家规模与今日注单活跃度，不含全局盈亏。 */
final class SiteCsDashboardOverviewBuilder
{
    /**
     * @return array<string, mixed>|null
     */
    public function build(AdminUser $admin): ?array
    {
        if (! $admin->hasPermissionCode('dashboard.view')) {
            return null;
        }

        $site = SiteDashboardSiteResolver::resolvePrimarySite($admin);
        if ($site === null) {
            return null;
        }

        $siteId = (int) $site->id;
        $siteCode = (string) $site->code;
        $today = now()->toDateString();
        $activity = $this->todayTicketStats($siteCode, $today);

        return [
            'admin_site_id' => $siteId,
            'site_code' => $siteCode,
            'site_name' => (string) $site->name,
            'player_count' => (int) Player::query()->where('site_code', $siteCode)->count(),
            'ticket_order_count_today' => $activity['order_count'],
            'active_player_count_today' => $activity['player_count'],
            'latest_ticket_at' => $activity['latest_at'],
        ];
    }

    /**
     * @return array{player_count: int, order_count: int, latest_at: ?string}
     */
    private function todayTicketStats(string $siteCode, string $today): array
    {
        $base = DB::table('ticket_orders as o')
            ->join('draws as d', 'd.id', '=', 'o.draw_id')
            ->join('players as p', 'p.id', '=', 'o.player_id')
            ->where('p.site_code', $siteCode)
            ->whereDate('d.business_date', $today);

        $latestAt = (clone $base)->max('o.created_at');

        return [
            'player_count' => (int) (clone $base)->distinct('o.player_id')->count('o.player_id'),
            'order_count' => (int) (clone $base)->count(),
            'latest_at' => $latestAt !== null ? Carbon::parse((string) $latestAt)->toIso8601String() : null,
        ];
    }
}
