import { prisma } from "@/lib/prisma";

type Plan = "FREE" | "PRO" | "BUSINESS";

const LIMITS: Record<Plan, {
  invoicesPerMonth: number;
  expensesPerMonth: number;
  members: number;
  bankAccounts: number;
}> = {
  FREE:     { invoicesPerMonth: 10,      expensesPerMonth: 50,      members: 1,  bankAccounts: 1 },
  PRO:      { invoicesPerMonth: 100,     expensesPerMonth: 500,     members: 5,  bankAccounts: 3 },
  BUSINESS: { invoicesPerMonth: Infinity, expensesPerMonth: Infinity, members: Infinity, bankAccounts: Infinity },
};

export function getPlanLimits(plan: Plan) {
  return LIMITS[plan];
}

export async function getOrgPlan(organizationId: string): Promise<Plan> {
  const sub = await prisma.subscription.findUnique({
    where: { organizationId },
    select: { plan: true, status: true },
  });
  if (!sub || sub.status === "CANCELED") return "FREE";
  return sub.plan as Plan;
}

export async function checkInvoiceLimit(organizationId: string): Promise<{ allowed: boolean; plan: Plan; used: number; limit: number }> {
  const plan = await getOrgPlan(organizationId);
  const limits = LIMITS[plan];

  if (limits.invoicesPerMonth === Infinity) return { allowed: true, plan, used: 0, limit: Infinity };

  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const used = await prisma.invoice.count({
    where: { organizationId, createdAt: { gte: startOfMonth } },
  });

  return { allowed: used < limits.invoicesPerMonth, plan, used, limit: limits.invoicesPerMonth };
}

export async function checkExpenseLimit(organizationId: string): Promise<{ allowed: boolean; plan: Plan; used: number; limit: number }> {
  const plan = await getOrgPlan(organizationId);
  const limits = LIMITS[plan];

  if (limits.expensesPerMonth === Infinity) return { allowed: true, plan, used: 0, limit: Infinity };

  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const used = await prisma.expense.count({
    where: { organizationId, createdAt: { gte: startOfMonth } },
  });

  return { allowed: used < limits.expensesPerMonth, plan, used, limit: limits.expensesPerMonth };
}

export async function checkMemberLimit(organizationId: string): Promise<{ allowed: boolean; plan: Plan; used: number; limit: number }> {
  const plan = await getOrgPlan(organizationId);
  const limits = LIMITS[plan];

  if (limits.members === Infinity) return { allowed: true, plan, used: 0, limit: Infinity };

  const used = await prisma.organizationMember.count({
    where: { organizationId, joinedAt: { not: null } },
  });

  return { allowed: used < limits.members, plan, used, limit: limits.members };
}
