/**
 * Tử Vi Số · Plan tiers (FREE / PREMIUM)
 *
 * Single source of truth for what each plan can do. Limits live here so
 * server actions (save chart, AI section, PDF export) and UI (paywall
 * banners, pricing page) read the same numbers.
 *
 * Pricing is mock — billing integration lands later. We keep `priceVnd`
 * so the pricing page renders a real number; manual upgrade flow uses
 * UpgradeRequest model + admin approval until Stripe/VNPay is wired.
 */

export type PlanKey = "FREE" | "PREMIUM";

export type PlanLimits = {
  /** How many saved charts the user can keep. -1 = unlimited */
  savedCharts: number;
  /** How many AI section reads per rolling 24h. -1 = unlimited */
  aiSectionsPerDay: number;
  /** How many AI chat messages per rolling 24h. -1 = unlimited */
  aiChatMessagesPerDay: number;
  /** Can export reading to PDF? */
  pdfExport: boolean;
  /** Can share lá số via public token? */
  shareLink: boolean;
  /** Custom branding on PDF (no watermark) */
  noWatermark: boolean;
};

export type Plan = {
  key: PlanKey;
  name: string;
  tagline: string;
  /** Vietnamese highlights for the pricing page */
  highlights: string[];
  /** Monthly price in VND (gross). 0 = free. */
  priceVnd: number;
  limits: PlanLimits;
};

export const PLANS: Record<PlanKey, Plan> = {
  FREE: {
    key: "FREE",
    name: "Thành Viên",
    tagline: "Đăng ký để mở khoá lưu lá số và đọc luận giải sâu hơn.",
    highlights: [
      "Lập lá số tử vi không giới hạn",
      "Lưu tối đa 3 lá số",
      "10 lượt đọc AI chuyên sâu / ngày",
      "20 tin nhắn AI hỏi đáp / ngày",
      "Phong thủy, lịch âm dương, thần số học",
    ],
    priceVnd: 0,
    limits: {
      savedCharts: 3,
      aiSectionsPerDay: 10,
      aiChatMessagesPerDay: 20,
      pdfExport: false,
      shareLink: true,
      noWatermark: false,
    },
  },
  PREMIUM: {
    key: "PREMIUM",
    name: "Premium",
    tagline: "Dành cho người dùng đào sâu và chia sẻ chuyên nghiệp.",
    highlights: [
      "Tất cả tính năng FREE",
      "Lưu lá số không giới hạn",
      "Đọc AI chuyên sâu không giới hạn",
      "Hỏi đáp AI không giới hạn",
      "Xuất luận giải PDF không watermark",
      "Ưu tiên hỗ trợ qua email",
    ],
    priceVnd: 99000,
    limits: {
      savedCharts: -1,
      aiSectionsPerDay: -1,
      aiChatMessagesPerDay: -1,
      pdfExport: true,
      shareLink: true,
      noWatermark: true,
    },
  },
};

/** Resolve plan from a user.plan column value with safe fallback to FREE. */
export function resolvePlan(planValue: string | null | undefined): Plan {
  if (planValue === "PREMIUM") return PLANS.PREMIUM;
  return PLANS.FREE;
}

/** Format VND price with thousand separators. */
export function formatVnd(n: number): string {
  return n.toLocaleString("vi-VN") + "₫";
}

/** Whether a numeric limit allows another action. -1 = unlimited. */
export function withinLimit(current: number, max: number): boolean {
  if (max < 0) return true;
  return current < max;
}
