import { prisma } from '../config/database.js';

export interface PlanLimits {
  maxRfcs: number;
  maxUsers: number;
  timbresIncluidosMes: number;
  features: string[];
}

export interface AddonDelta {
  maxRfcs?: number;
  maxUsers?: number;
  timbresIncluidosMes?: number;
  features?: string[];
}

export function computeEffectiveLimits(baseLimits: PlanLimits, addonDeltas: AddonDelta[]): PlanLimits {
  const result: PlanLimits = {
    maxRfcs: baseLimits.maxRfcs,
    maxUsers: baseLimits.maxUsers,
    timbresIncluidosMes: baseLimits.timbresIncluidosMes,
    features: [...baseLimits.features],
  };

  for (const delta of addonDeltas) {
    if (delta.maxRfcs) {
      result.maxRfcs = result.maxRfcs === -1 ? -1 : result.maxRfcs + delta.maxRfcs;
    }
    if (delta.maxUsers) {
      result.maxUsers = result.maxUsers === -1 ? -1 : result.maxUsers + delta.maxUsers;
    }
    if (delta.timbresIncluidosMes) {
      result.timbresIncluidosMes += delta.timbresIncluidosMes;
    }
    if (delta.features) {
      for (const f of delta.features) {
        if (!result.features.includes(f)) result.features.push(f);
      }
    }
  }

  return result;
}

export async function listPlans(verticalProfile?: string) {
  const where: any = { active: true };
  if (verticalProfile) where.verticalProfile = verticalProfile;

  const plans = await (prisma as any).planCatalogo.findMany({
    where,
    orderBy: { precioBase: 'asc' },
  });

  return plans.map((p: any) => ({
    id: p.id,
    codename: p.codename,
    nombre: p.nombre,
    verticalProfile: p.verticalProfile,
    precioBase: Number(p.precioBase),
    frecuencia: p.frecuencia,
    limits: p.limits as PlanLimits,
  }));
}

export async function listAddons(verticalProfile?: string) {
  const where: any = { active: true };
  if (verticalProfile) {
    where.OR = [
      { verticalProfile },
      { verticalProfile: null },
    ];
  }

  const addons = await (prisma as any).planAddonCatalogo.findMany({
    where,
    orderBy: { precio: 'asc' },
  });

  return addons.map((a: any) => ({
    id: a.id,
    codename: a.codename,
    nombre: a.nombre,
    verticalProfile: a.verticalProfile,
    precio: Number(a.precio),
    frecuencia: a.frecuencia,
    delta: a.delta as AddonDelta,
  }));
}

export async function getPlanByCodename(codename: string) {
  const plan = await (prisma as any).planCatalogo.findUnique({ where: { codename } });
  if (!plan) return null;
  return {
    id: plan.id,
    codename: plan.codename,
    nombre: plan.nombre,
    verticalProfile: plan.verticalProfile,
    precioBase: Number(plan.precioBase),
    frecuencia: plan.frecuencia,
    limits: plan.limits as PlanLimits,
  };
}
