<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class AuditAgentLineDataCommand extends Command
{
    protected $signature = 'lottery:audit-agent-lines {--json : Output JSON only}';

    protected $description = '盘点代理线路历史数据异常（只读）';

    public function handle(): int
    {
        $sites = DB::table('admin_sites')->orderBy('id')->get(['id', 'code', 'name']);
        $issues = [];

        foreach ($sites as $site) {
            $siteId = (int) $site->id;
            $roots = DB::table('agent_nodes')
                ->where('admin_site_id', $siteId)
                ->where('depth', 0)
                ->get(['id', 'code', 'name']);

            if ($roots->isEmpty()) {
                $issues[] = [
                    'type' => 'site_without_root',
                    'admin_site_id' => $siteId,
                    'site_code' => (string) $site->code,
                    'message' => '站点无 depth=0 根代理节点',
                ];
            } elseif ($roots->count() > 1) {
                $issues[] = [
                    'type' => 'site_multiple_roots',
                    'admin_site_id' => $siteId,
                    'site_code' => (string) $site->code,
                    'root_ids' => $roots->pluck('id')->all(),
                    'message' => '站点存在多个根节点',
                ];
            } else {
                $root = $roots->first();
                $expectedCode = (string) $site->code;
                $rootCode = (string) $root->code;
                if ($rootCode !== $expectedCode && $rootCode !== 'root-'.$expectedCode) {
                    $issues[] = [
                        'type' => 'root_code_mismatch',
                        'admin_site_id' => $siteId,
                        'site_code' => $expectedCode,
                        'root_code' => $rootCode,
                        'message' => '根节点 code 与 site.code 不一致',
                    ];
                }

                $loginCount = (int) DB::table('admin_user_agents')
                    ->where('agent_node_id', (int) $root->id)
                    ->count();
                if ($loginCount === 0) {
                    $issues[] = [
                        'type' => 'root_without_login',
                        'admin_site_id' => $siteId,
                        'agent_node_id' => (int) $root->id,
                        'message' => '根代理无绑定后台账号',
                    ];
                }
            }

            $businessAgents = DB::table('agent_nodes')
                ->where('admin_site_id', $siteId)
                ->where('depth', '>', 0)
                ->count();
            if ($businessAgents > 0 && $roots->count() === 1) {
                // informational only for multi-agent-under-one-site report
            }
        }

        $sitesWithManyBusinessAgents = DB::table('agent_nodes')
            ->select('admin_site_id', DB::raw('count(*) as cnt'))
            ->where('depth', '>', 0)
            ->groupBy('admin_site_id')
            ->havingRaw('count(*) > 0')
            ->get();

        foreach ($sitesWithManyBusinessAgents as $row) {
            $siteId = (int) $row->admin_site_id;
            $siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
            $rootCount = DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->count();
            if ($rootCount === 1 && (int) $row->cnt >= 1) {
                $issues[] = [
                    'type' => 'site_has_business_agents',
                    'admin_site_id' => $siteId,
                    'site_code' => $siteCode,
                    'business_agent_count' => (int) $row->cnt,
                    'message' => '站点下存在下级业务代理（需确认是否应拆站）',
                ];
            }
        }

        if ($this->option('json')) {
            $this->line(json_encode(['issues' => $issues], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

            return self::SUCCESS;
        }

        $this->info('Agent line audit: '.count($issues).' issue(s)');
        foreach ($issues as $issue) {
            $this->line('- ['.$issue['type'].'] '.$issue['message'].' (site: '.($issue['site_code'] ?? $issue['admin_site_id'] ?? '?').')');
        }

        return self::SUCCESS;
    }
}
