/**
 * Billing & usage (ADM-004): monthly subscription per workspace, tiered by contacts and seats, plus metered
 * SMS, WhatsApp, email and AI credits. Stripe for US/AU, SSLCommerz or bKash for Bangladesh.
 */
import { and, eq, isNull, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { period } from "@/lib/util";

export const PLANS: Record<string, { name: string; price: Record<string, number>; contacts: number; seats: number; included: Record<string, number>; overage: Record<string, Record<string, number>> }> = {
  starter: { name: "Starter", price: { BDT: 600000, USD: 5000, AUD: 7900 }, contacts: 2500, seats: 3, included: { sms: 500, whatsapp: 500, email: 10000, ai_credits: 200 }, overage: { BDT: { sms: 45, whatsapp: 90, email: 2, ai_credits: 100, contacts: 50, seats: 150000 }, USD: { sms: 2, whatsapp: 3, email: 1, ai_credits: 2, contacts: 1, seats: 1500 }, AUD: { sms: 4, whatsapp: 5, email: 1, ai_credits: 3, contacts: 1, seats: 2200 } } },
  growth: { name: "Growth", price: { BDT: 1200000, USD: 10000, AUD: 15500 }, contacts: 15000, seats: 10, included: { sms: 3000, whatsapp: 3000, email: 50000, ai_credits: 1500 }, overage: { BDT: { sms: 40, whatsapp: 80, email: 1, ai_credits: 90, contacts: 40, seats: 120000 }, USD: { sms: 2, whatsapp: 3, email: 1, ai_credits: 2, contacts: 1, seats: 1200 }, AUD: { sms: 3, whatsapp: 4, email: 1, ai_credits: 3, contacts: 1, seats: 1800 } } },
  enterprise: { name: "Enterprise", price: { BDT: 3000000, USD: 25000, AUD: 38900 }, contacts: 100000, seats: 50, included: { sms: 10000, whatsapp: 10000, email: 250000, ai_credits: 6000 }, overage: { BDT: { sms: 35, whatsapp: 70, email: 1, ai_credits: 80, contacts: 30, seats: 100000 }, USD: { sms: 1, whatsapp: 2, email: 1, ai_credits: 1, contacts: 1, seats: 1000 }, AUD: { sms: 2, whatsapp: 3, email: 1, ai_credits: 2, contacts: 1, seats: 1500 } } },
  agency: { name: "Enterprise (legacy agency)", price: { BDT: 3000000, USD: 25000, AUD: 38900 }, contacts: 100000, seats: 50, included: { sms: 10000, whatsapp: 10000, email: 250000, ai_credits: 6000 }, overage: { BDT: { sms: 35, whatsapp: 70, email: 1, ai_credits: 80, contacts: 30, seats: 100000 }, USD: { sms: 1, whatsapp: 2, email: 1, ai_credits: 1, contacts: 1, seats: 1000 }, AUD: { sms: 2, whatsapp: 3, email: 1, ai_credits: 2, contacts: 1, seats: 1500 } } },
};

export async function recordUsage(ctx: Pick<Ctx, "db" | "workspace">, meter: string, quantity = 1) {
  await ctx.db.insert(schema.usageRecords).values({ workspaceId: ctx.workspace.id, meter, quantity, period: period() });
}

export async function usageForPeriod(ctx: Pick<Ctx, "db" | "workspace">, p = period()) {
  const rows = await ctx.db.select({ meter: schema.usageRecords.meter, q: sql<number>`sum(${schema.usageRecords.quantity})::int` }).from(schema.usageRecords)
    .where(and(eq(schema.usageRecords.workspaceId, ctx.workspace.id), eq(schema.usageRecords.period, p))).groupBy(schema.usageRecords.meter);
  const usage: Record<string, number> = Object.fromEntries(rows.map((r) => [r.meter, r.q]));
  const [{ contacts }] = await ctx.db.select({ contacts: sql<number>`count(*)::int` }).from(schema.contacts).where(and(eq(schema.contacts.workspaceId, ctx.workspace.id), isNull(schema.contacts.deletedAt))) as [{ contacts: number }];
  const [{ seats }] = await ctx.db.select({ seats: sql<number>`count(*)::int` }).from(schema.memberships).where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.active, true))) as [{ seats: number }];
  return { ...usage, contacts, seats } as Record<string, number>;
}

export function buildInvoiceLines(planKey: string, currency: string, usage: Record<string, number>) {
  const plan = PLANS[planKey] ?? PLANS.growth!;
  const cur = plan.price[currency] !== undefined ? currency : "USD";
  const lines: { label: string; quantity: number; unit: number; total: number }[] = [{ label: `${plan.name} plan`, quantity: 1, unit: plan.price[cur]!, total: plan.price[cur]! }];
  for (const meter of ["sms", "whatsapp", "email", "ai_credits"]) {
    const over = Math.max(0, (usage[meter] ?? 0) - (plan.included[meter] ?? 0));
    if (over > 0) lines.push({ label: `${meter.replace("_", " ").toUpperCase()} overage`, quantity: over, unit: plan.overage[cur]![meter]!, total: over * plan.overage[cur]![meter]! });
  }
  const extraContacts = Math.max(0, (usage.contacts ?? 0) - plan.contacts);
  if (extraContacts) {
    const blocks = Math.ceil(extraContacts / 100);
    lines.push({ label: "Additional contacts (per 100)", quantity: blocks, unit: plan.overage[cur]!.contacts! * 100, total: blocks * plan.overage[cur]!.contacts! * 100 });
  }
  const extraSeats = Math.max(0, (usage.seats ?? 0) - plan.seats);
  if (extraSeats) lines.push({ label: "Additional seats", quantity: extraSeats, unit: plan.overage[cur]!.seats!, total: extraSeats * plan.overage[cur]!.seats! });
  return { lines, currency: cur, amount: lines.reduce((s, l) => s + l.total, 0) };
}

/** Close a period: usage overage bills automatically (monthly cron). */
export async function generateInvoice(ctx: Ctx, p: string) {
  const existing = await ctx.db.query.invoices.findFirst({ where: and(eq(schema.invoices.workspaceId, ctx.workspace.id), eq(schema.invoices.period, p)) });
  if (existing) return existing;
  const usage = await usageForPeriod(ctx, p);
  const { lines, currency, amount } = buildInvoiceLines(ctx.workspace.plan, ctx.workspace.currency, usage);
  const provider = currency === "BDT" ? "sslcommerz" : "stripe";
  const [inv] = await ctx.db.insert(schema.invoices).values({ workspaceId: ctx.workspace.id, period: p, provider, amount, currency, lines }).returning();
  await audit(ctx, "create", "invoice", inv!.id, undefined, { period: p, amount, currency });
  return inv!;
}

export async function markInvoicePaid(ctx: Ctx, invoiceId: string | undefined, externalId: string | undefined) {
  if (!invoiceId) return;
  const [inv] = await ctx.db.update(schema.invoices).set({ status: "paid", externalId: externalId ?? null, updatedAt: new Date() })
    .where(and(eq(schema.invoices.id, invoiceId), eq(schema.invoices.workspaceId, ctx.workspace.id))).returning();
  if (inv) await audit(ctx, "paid", "invoice", inv.id, undefined, { externalId });
}

/** AI credits metered per workspace (AI platform rules: cost control). */
export async function aiCreditsRemaining(ctx: Pick<Ctx, "db" | "workspace">) {
  const plan = PLANS[ctx.workspace.plan] ?? PLANS.growth!;
  const allowance = ctx.workspace.settings?.aiCreditsMonthly ?? plan.included.ai_credits ?? 0;
  const u = await usageForPeriod(ctx);
  return { allowance, used: u.ai_credits ?? 0, remaining: Math.max(0, allowance - (u.ai_credits ?? 0)) };
}
