/**
 * GET /api/me/plan?brandId=X
 * ───────────────────────────
 * Returns the current plan + entitlements for the given brand. Used
 * by the usePlan() hook and the upgrade modal to render "current
 * plan vs recommended" comparisons.
 *
 * Shape:
 *   {
 *     plan: "growth",
 *     billingCycle: "monthly",
 *     planExpiresAt: "..." | null,
 *     effectivePlan: "growth",       // trial may resolve to pro/growth
 *     limits: { ... },                // from plan-config.PLANS
 *     usage: {
 *       brandsUsed: 2,
 *       aiCreditsUsed: 45,
 *       aiCreditsResetAt: "..." | null,
 *     }
 *   }
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { PLANS, resolveEffectivePlan, type PlanId } from "@/lib/plan-config";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true, _count: { select: { brands: true } } } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const plan = (brand.plan as PlanId) ?? "trial";
  const effectivePlan = resolveEffectivePlan({ plan, planExpiresAt: brand.planExpiresAt });
  const planData = PLANS[effectivePlan];

  // Real usage counts from the actual tables — replaces the stale
  // brand.aiCreditsUsed counter column that was never incremented.
  const orgBrandIds = await prisma.brand.findMany({
    where: { orgId: brand.orgId },
    select: { id: true },
  }).then((bs) => bs.map((b) => b.id));

  const billingStart = brand.aiCreditsResetAt
    ?? brand.planStartedAt
    ?? new Date(new Date().getFullYear(), new Date().getMonth(), 1);

  const [aiCredits, rankKeywords, contentBriefs, serpLookups, siteTagEvents, emailSchedules] = await Promise.all([
    prisma.aiInteraction.count({
      where: { brandId: { in: orgBrandIds }, timestamp: { gte: billingStart } },
    }).catch(() => brand.aiCreditsUsed),
    prisma.trackedKeyword.count({
      where: { brandId: { in: orgBrandIds }, isActive: true },
    }).catch(() => 0),
    prisma.contentBrief.count({
      where: { brandId: { in: orgBrandIds }, createdAt: { gte: billingStart } },
    }).catch(() => 0),
    prisma.keywordResearch.count({
      where: { brandId: { in: orgBrandIds }, createdAt: { gte: billingStart } },
    }).catch(() => 0),
    prisma.trackedEvent.count({
      where: {
        trackedSite: { brandId: { in: orgBrandIds } },
        timestamp: { gte: billingStart },
      },
    }).catch(() => 0),
    prisma.emailReportSchedule.count({
      where: { brandId: { in: orgBrandIds } },
    }).catch(() => 0),
  ]);

  return NextResponse.json({
    plan,
    effectivePlan,
    billingCycle: brand.billingCycle,
    planStartedAt: brand.planStartedAt?.toISOString() ?? null,
    planExpiresAt: brand.planExpiresAt?.toISOString() ?? null,
    limits: planData.limits,
    features: planData.features,
    usage: {
      brandsUsed: brand.organization._count.brands,
      aiCreditsUsed: aiCredits,
      aiCreditsResetAt: brand.aiCreditsResetAt?.toISOString() ?? null,
      rankKeywordsUsed: rankKeywords,
      contentBriefsUsed: contentBriefs,
      serpLookupsUsed: serpLookups,
      siteTagEventsUsed: siteTagEvents,
      emailSchedulesUsed: emailSchedules,
    },
  });
}
