/**
 * billing/config.ts — Razorpay configuration + premium grant constants.
 *
 * Reads the four required env vars. Helpers throw at call time (not module load)
 * so the rest of the app still boots if billing isn't configured yet — only the
 * billing routes fail loudly.
 */

// ─── Premium grant (what an active subscription gives a family) ───────────────
// These are written onto families.tier / max_members / max_children by the
// webhook. The existing quota.ts guards then enforce them via isPaidFamily().
export const PREMIUM_TIER = "pro";
export const PREMIUM_STORAGE_BYTES = 50 * 1024 ** 3; // 50 GiB
export const PREMIUM_MEMBER_LIMIT = 6;
export const PREMIUM_CHILD_LIMIT = 3;
export const PREMIUM_PRICE_PAISE = 19900; // ₹199.00
export const PREMIUM_PLAN_NAME = "Tia Premium";

export const RAZORPAY_API_BASE = "https://api.razorpay.com/v1";

interface RazorpayConfig {
  keyId: string;
  keySecret: string;
  webhookSecret: string;
  planId: string;
}

/**
 * Returns the Razorpay config, throwing if any required var is missing.
 * Call inside route handlers so a misconfiguration is a clear 500, not a
 * boot crash for the whole app.
 */
export function getRazorpayConfig(): RazorpayConfig {
  const keyId = process.env.RAZORPAY_KEY_ID;
  const keySecret = process.env.RAZORPAY_KEY_SECRET;
  const webhookSecret = process.env.RAZORPAY_WEBHOOK_SECRET;
  const planId = process.env.RAZORPAY_PLAN_ID;

  const missing: string[] = [];
  if (!keyId) missing.push("RAZORPAY_KEY_ID");
  if (!keySecret) missing.push("RAZORPAY_KEY_SECRET");
  if (!webhookSecret) missing.push("RAZORPAY_WEBHOOK_SECRET");
  if (!planId) missing.push("RAZORPAY_PLAN_ID");
  if (missing.length) {
    throw new Error(`Razorpay not configured — missing env: ${missing.join(", ")}`);
  }

  return { keyId: keyId!, keySecret: keySecret!, webhookSecret: webhookSecret!, planId: planId! };
}

/** HTTP Basic auth header value for Razorpay REST calls. */
export function razorpayAuthHeader(cfg: Pick<RazorpayConfig, "keyId" | "keySecret">): string {
  return "Basic " + Buffer.from(`${cfg.keyId}:${cfg.keySecret}`).toString("base64");
}
