<?php

namespace App\Services\AgentSettlement;

use App\Models\AdminUser;
use App\Support\AdminAgentSettlementScope;
use App\Support\AdminDataScope;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/** §21.12 信用占成盘报表最低集。 */
final class AgentSettlementReportQueryService
{
    /**
     * @return array<string, mixed>
     */
    public function summary(AdminUser $admin, int $periodId = 0): array
    {
        $query = DB::table('settlement_bills');
        AdminAgentSettlementScope::applyToBillsQuery($query, $admin);
        if ($periodId > 0) {
            $query->where('settlement_period_id', $periodId);
        }
        $rows = $query->get();

        return [
            'bill_count' => $rows->count(),
            'total_net' => (int) $rows->sum('net_amount'),
            'total_unpaid' => (int) $rows->sum('unpaid_amount'),
            'overdue_count' => $rows->where('status', 'overdue')->count(),
            'platform_rounding_total' => (int) $rows->sum('platform_rounding_adjustment'),
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function playerWinLoss(AdminUser $admin, int $periodId, string $periodStart, string $periodEnd): array
    {
        $siteCode = $this->siteCodeForAdmin($admin, $periodId);

        $query = DB::table('share_ledger as sl')
            ->join('players as p', 'p.id', '=', 'sl.player_id')
            ->leftJoin('ticket_items as ti', 'ti.id', '=', 'sl.ticket_item_id')
            ->where('p.site_code', $siteCode)
            ->whereBetween('sl.settled_at', [$periodStart, $periodEnd])
            ->whereNull('sl.reversal_of_id');
        $this->applyPlayerSubtree($query, $admin, 'p');

        return $query
            ->groupBy('sl.player_id', 'p.username', 'p.agent_node_id', 'ti.play_code')
            ->selectRaw('sl.player_id, p.username, p.agent_node_id, COALESCE(ti.play_code, ?) as game_type', ['*'])
            ->selectRaw('SUM(sl.game_win_loss) as game_win_loss')
            ->selectRaw('SUM(sl.basic_rebate) as basic_rebate')
            ->orderByDesc('game_win_loss')
            ->get()
            ->map(static fn (object $r): array => [
                'player_id' => (int) $r->player_id,
                'username' => (string) ($r->username ?? ''),
                'agent_node_id' => (int) $r->agent_node_id,
                'game_type' => (string) $r->game_type,
                'game_win_loss' => (int) $r->game_win_loss,
                'basic_rebate' => (int) $r->basic_rebate,
            ])
            ->all();
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function agentShare(AdminUser $admin, string $periodStart, string $periodEnd): array
    {
        $siteCode = $this->siteCodeForAdmin($admin, 0);

        $query = DB::table('share_ledger as sl')
            ->join('players as p', 'p.id', '=', 'sl.player_id')
            ->where('p.site_code', $siteCode)
            ->whereBetween('sl.settled_at', [$periodStart, $periodEnd])
            ->whereNull('sl.reversal_of_id');
        $this->applyAgentSubtree($query, $admin, 'sl.agent_node_id');

        return $query
            ->groupBy('sl.agent_node_id')
            ->selectRaw('sl.agent_node_id, SUM(sl.game_win_loss) as game_win_loss, SUM(sl.basic_rebate) as basic_rebate, COUNT(*) as entry_count')
            ->orderByDesc('game_win_loss')
            ->get()
            ->map(static fn (object $r): array => [
                'agent_node_id' => (int) $r->agent_node_id,
                'game_win_loss' => (int) $r->game_win_loss,
                'basic_rebate' => (int) $r->basic_rebate,
                'entry_count' => (int) $r->entry_count,
            ])
            ->all();
    }

    /**
     * @return array<string, mixed>
     */
    public function rebate(AdminUser $admin, int $periodId, string $periodStart, string $periodEnd): array
    {
        $siteCode = $this->siteCodeForAdmin($admin, $periodId);

        $base = DB::table('rebate_records as rr')
            ->join('players as p', 'p.id', '=', 'rr.player_id')
            ->where('p.site_code', $siteCode);
        $this->applyPlayerSubtree($base, $admin, 'p');

        $accrued = (clone $base)->where('rr.status', 'accrued')->sum('rr.rebate_amount');
        $inBill = (clone $base)->where('rr.status', 'in_bill')->sum('rr.rebate_amount');
        $settled = (clone $base)->where('rr.status', 'settled')->sum('rr.rebate_amount');

        $allocatedQuery = DB::table('rebate_allocations as ra')
            ->join('rebate_records as rr', 'rr.id', '=', 'ra.rebate_record_id')
            ->join('players as p', 'p.id', '=', 'rr.player_id')
            ->where('p.site_code', $siteCode)
            ->when($periodId > 0, fn (Builder $q) => $q->where('rr.settlement_period_id', $periodId));
        $this->applyPlayerSubtree($allocatedQuery, $admin, 'p');
        $allocated = (int) $allocatedQuery->sum('ra.allocated_amount');

        return [
            'accrued_total' => (int) $accrued,
            'in_bill_total' => (int) $inBill,
            'settled_total' => (int) $settled,
            'allocated_total' => $allocated,
            'by_type' => tap(
                DB::table('rebate_records as rr')
                    ->join('players as p', 'p.id', '=', 'rr.player_id')
                    ->where('p.site_code', $siteCode)
                    ->whereBetween('rr.created_at', [$periodStart, $periodEnd]),
                fn (Builder $q) => $this->applyPlayerSubtree($q, $admin, 'p'),
            )
                ->groupBy('rr.rebate_type', 'rr.status')
                ->selectRaw('rr.rebate_type, rr.status, SUM(rr.rebate_amount) as total, COUNT(*) as cnt')
                ->get()
                ->map(static fn (object $r): array => [
                    'rebate_type' => (string) $r->rebate_type,
                    'status' => (string) $r->status,
                    'total' => (int) $r->total,
                    'count' => (int) $r->cnt,
                ])
                ->all(),
        ];
    }

    /**
     * @return array{agents: list<array<string, mixed>>, players: list<array<string, mixed>>}
     */
    public function credit(AdminUser $admin): array
    {
        $siteCode = $this->siteCodeForAdmin($admin, 0);

        $agentsQuery = DB::table('agent_profiles as ap')
            ->join('agent_nodes as an', 'an.id', '=', 'ap.agent_node_id')
            ->join('admin_sites as s', 's.id', '=', 'an.admin_site_id')
            ->where('s.code', $siteCode);
        $this->applyAgentSubtree($agentsQuery, $admin, 'ap.agent_node_id');

        $agents = $agentsQuery
            ->selectRaw('ap.agent_node_id, an.code, an.name, ap.credit_limit, ap.allocated_credit, (ap.credit_limit - ap.allocated_credit) as available_credit')
            ->orderBy('an.depth')
            ->get()
            ->map(static fn (object $r): array => [
                'agent_node_id' => (int) $r->agent_node_id,
                'code' => (string) $r->code,
                'name' => (string) $r->name,
                'credit_limit' => (int) $r->credit_limit,
                'allocated_credit' => (int) $r->allocated_credit,
                'available_credit' => (int) $r->available_credit,
            ])
            ->all();

        $playersQuery = DB::table('player_credit_accounts as pc')
            ->join('players as p', 'p.id', '=', 'pc.player_id')
            ->where('p.site_code', $siteCode);
        $this->applyPlayerSubtree($playersQuery, $admin, 'p');

        $players = $playersQuery
            ->selectRaw('pc.player_id, p.username, pc.credit_limit, pc.used_credit, pc.frozen_credit, (pc.credit_limit - pc.used_credit - pc.frozen_credit) as available_credit')
            ->orderByDesc('pc.used_credit')
            ->limit(500)
            ->get()
            ->map(static fn (object $r): array => [
                'player_id' => (int) $r->player_id,
                'username' => (string) ($r->username ?? ''),
                'credit_limit' => (int) $r->credit_limit,
                'used_credit' => (int) $r->used_credit,
                'frozen_credit' => (int) $r->frozen_credit,
                'available_credit' => max(0, (int) $r->available_credit),
            ])
            ->all();

        return ['agents' => $agents, 'players' => $players];
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function unpaidBills(AdminUser $admin, int $periodId = 0): array
    {
        $query = DB::table('settlement_bills as sb')
            ->join('settlement_periods as sp', 'sp.id', '=', 'sb.settlement_period_id')
            ->where('sb.unpaid_amount', '>', 0)
            ->whereIn('sb.status', ['pending_confirm', 'confirmed', 'partial_paid', 'overdue']);
        AdminAgentSettlementScope::applyToBillsQuery($query, $admin, 'sb');
        if ($periodId > 0) {
            $query->where('sb.settlement_period_id', $periodId);
        }

        return $query
            ->select([
                'sb.id',
                'sb.bill_type',
                'sb.owner_type',
                'sb.owner_id',
                'sb.counterparty_type',
                'sb.counterparty_id',
                'sb.net_amount',
                'sb.unpaid_amount',
                'sb.status',
                'sp.period_start',
                'sp.period_end',
            ])
            ->orderByDesc('sb.unpaid_amount')
            ->get()
            ->map(static fn (object $r): array => [
                'bill_id' => (int) $r->id,
                'bill_type' => (string) $r->bill_type,
                'owner_type' => (string) $r->owner_type,
                'owner_id' => (int) $r->owner_id,
                'counterparty_type' => (string) $r->counterparty_type,
                'counterparty_id' => (int) $r->counterparty_id,
                'net_amount' => (int) $r->net_amount,
                'unpaid_amount' => (int) $r->unpaid_amount,
                'status' => (string) $r->status,
                'period_start' => (string) $r->period_start,
                'period_end' => (string) $r->period_end,
            ])
            ->all();
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function overdue(AdminUser $admin): array
    {
        $query = DB::table('settlement_bills as sb')
            ->join('settlement_periods as sp', 'sp.id', '=', 'sb.settlement_period_id')
            ->where('sb.status', 'overdue')
            ->where('sb.unpaid_amount', '>', 0);
        AdminAgentSettlementScope::applyToBillsQuery($query, $admin, 'sb');

        return $query
            ->select([
                'sb.id',
                'sb.bill_type',
                'sb.owner_type',
                'sb.owner_id',
                'sb.unpaid_amount',
                'sb.updated_at',
                'sp.period_end',
            ])
            ->orderBy('sb.updated_at')
            ->get()
            ->map(static function (object $r): array {
                $days = Carbon::parse((string) $r->updated_at)->diffInDays(now());

                return [
                    'bill_id' => (int) $r->id,
                    'bill_type' => (string) $r->bill_type,
                    'owner_type' => (string) $r->owner_type,
                    'owner_id' => (int) $r->owner_id,
                    'unpaid_amount' => (int) $r->unpaid_amount,
                    'overdue_days' => $days,
                    'period_end' => (string) $r->period_end,
                ];
            })
            ->all();
    }

    /**
     * @return array<string, mixed>
     */
    public function platformPnl(AdminUser $admin, int $periodId): array
    {
        $query = DB::table('settlement_bills as sb')
            ->where('sb.settlement_period_id', $periodId)
            ->where(function (Builder $q): void {
                $q->where('sb.counterparty_type', 'platform')
                    ->orWhere('sb.owner_type', 'platform');
            });
        AdminAgentSettlementScope::applyToBillsQuery($query, $admin, 'sb');
        $rows = $query->get();

        return [
            'platform_bill_net' => (int) $rows->sum('net_amount'),
            'platform_rounding_adjustment' => (int) $rows->sum('platform_rounding_adjustment'),
            'share_profit_meta' => (int) $rows->sum(fn (object $r): int => (int) (json_decode((string) ($r->meta_json ?? '{}'), true)['platform_share_profit'] ?? 0)),
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function drawPeriod(AdminUser $admin, string $periodStart, string $periodEnd): array
    {
        $siteCode = $this->siteCodeForAdmin($admin, 0);

        $query = DB::table('share_ledger as sl')
            ->join('ticket_items as ti', 'ti.id', '=', 'sl.ticket_item_id')
            ->join('players as p', 'p.id', '=', 'sl.player_id')
            ->join('draws as d', 'd.id', '=', 'ti.draw_id')
            ->where('p.site_code', $siteCode)
            ->whereBetween('sl.settled_at', [$periodStart, $periodEnd])
            ->whereNull('sl.reversal_of_id');
        $this->applyPlayerSubtree($query, $admin, 'p');

        return $query
            ->groupBy('ti.draw_id', 'd.draw_no')
            ->selectRaw('ti.draw_id, d.draw_no, SUM(sl.game_win_loss) as game_win_loss, SUM(sl.basic_rebate) as basic_rebate, COUNT(*) as ticket_count')
            ->orderBy('d.draw_no')
            ->get()
            ->map(static fn (object $r): array => [
                'draw_id' => (int) $r->draw_id,
                'draw_no' => (string) $r->draw_no,
                'game_win_loss' => (int) $r->game_win_loss,
                'basic_rebate' => (int) $r->basic_rebate,
                'ticket_count' => (int) $r->ticket_count,
            ])
            ->all();
    }

    private function applyPlayerSubtree(Builder $query, AdminUser $admin, string $alias = 'p'): void
    {
        AdminAgentSettlementScope::applyDirectPlayersToAlias($query, $admin, $alias);
    }

    private function applyAgentSubtree(Builder $query, AdminUser $admin, string $agentNodeColumn): void
    {
        $actorId = AdminAgentSettlementScope::boundAgentNodeId($admin);
        if ($actorId === null) {
            return;
        }

        $query->where($agentNodeColumn, $actorId);
    }

    private function siteCodeForAdmin(AdminUser $admin, int $periodId): string
    {
        if ($periodId > 0) {
            $siteId = (int) DB::table('settlement_periods')->where('id', $periodId)->value('admin_site_id');

            return (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
        }

        $siteId = (int) ($admin->admin_site_id ?? 0);
        if ($siteId > 0) {
            return (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
        }

        return (string) DB::table('admin_sites')->where('is_default', true)->value('code');
    }
}
