/**
 * GET /api/admin/organizations/[orgId] — org detail with per-brand usage stats.
 */
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(_req: Request, { params }: { params: { orgId: string } }) {
  const auth = await requireAdmin();
  if (!auth.ok) return NextResponse.json({ error: "Forbidden" }, { status: auth.status });

  const org = await prisma.organization.findUnique({
    where: { id: params.orgId },
    include: {
      brands: {
        include: {
          integrations: { select: { integrationId: true, connected: true, lastSynced: true } },
          trackedSite: { select: { id: true, siteId: true, status: true, firstEventAt: true, lastEventAt: true } },
        },
      },
      memberships: {
        include: { user: { select: { id: true, name: true, email: true, image: true, createdAt: true } } },
        orderBy: { createdAt: "asc" },
      },
    },
  });
  if (!org) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const d30 = new Date(Date.now() - 30 * 86_400_000);
  const brandIds = org.brands.map((b) => b.id);
  const siteIds = org.brands.map((b) => b.trackedSite?.id).filter(Boolean) as string[];

  const [aiUsage, ...perBrandStats] = await Promise.all([
    prisma.aiUsageLog.aggregate({
      where: { brandId: { in: brandIds }, timestamp: { gte: d30 } },
      _count: true,
      _sum: { estimatedCost: true },
    }).catch(() => ({ _count: 0, _sum: { estimatedCost: null } })),
    ...org.brands.map(async (brand) => {
      const siteId = brand.trackedSite?.id;
      const [sessions, conversions, gsc, keywords, briefs, plugins] = await Promise.all([
        siteId
          ? prisma.trackedSession.count({ where: { trackedSiteId: siteId, startedAt: { gte: d30 } } }).catch(() => 0)
          : 0,
        // intentionally unfiltered: admin-only endpoint; needs raw or all-time counts
        prisma.siteConversion.count({ where: { brandId: brand.id, timestamp: { gte: d30 } } }).catch(() => 0),
        prisma.gscPage.aggregate({
          where: { brandId: brand.id, date: { gte: new Date(Date.now() - 28 * 86_400_000) } },
          _sum: { clicks: true, impressions: true },
        }).catch(() => ({ _sum: { clicks: null, impressions: null } })),
        prisma.trackedKeyword.count({ where: { brandId: brand.id, isActive: true } }).catch(() => 0),
        prisma.contentBrief.count({ where: { brandId: brand.id } }).catch(() => 0),
        siteId
          ? prisma.trackedEvent.findMany({
              where: { trackedSiteId: siteId, eventType: "plugin_detected" },
              distinct: ["metadata" as never],
              select: { metadata: true },
              take: 20,
            }).catch(() => [])
          : [],
      ]);
      return {
        brandId: brand.id,
        sessions30d: sessions,
        conversions30d: conversions,
        gscClicks28d: gsc._sum.clicks ?? 0,
        gscImpressions28d: gsc._sum.impressions ?? 0,
        trackedKeywords: keywords,
        contentBriefs: briefs,
        pluginsDetected: (plugins as Array<{ metadata: unknown }>)
          .map((p) => {
            const m = p.metadata as Record<string, unknown> | null;
            return (m?.plugin as string) ?? (m?.plugin_key as string) ?? null;
          })
          .filter(Boolean),
      };
    }),
  ]);

  const statsMap = new Map(perBrandStats.map((s) => [s.brandId, s]));

  return NextResponse.json({
    organization: {
      ...org,
      brands: org.brands.map((b) => ({
        id: b.id,
        name: b.name,
        domain: b.domain,
        plan: b.plan,
        industry: b.industry,
        createdAt: b.createdAt.toISOString(),
        integrations: b.integrations,
        siteTag: b.trackedSite
          ? {
              siteId: b.trackedSite.siteId,
              status: b.trackedSite.status,
              firstEventAt: b.trackedSite.firstEventAt?.toISOString() ?? null,
              lastEventAt: b.trackedSite.lastEventAt?.toISOString() ?? null,
            }
          : null,
        stats: statsMap.get(b.id) ?? null,
      })),
      memberships: org.memberships.map((m) => ({
        role: m.role,
        joinedAt: m.createdAt.toISOString(),
        user: m.user,
      })),
    },
    aiUsage: {
      calls: typeof aiUsage._count === "number" ? aiUsage._count : 0,
      cost: Math.round((aiUsage._sum.estimatedCost ?? 0) * 100) / 100,
    },
  });
}
