// Environment configuration. Required secrets fail fast at boot.
// Stripe is intentionally optional so the server runs before billing is wired.

function required(name) {
  const v = process.env[name];
  if (!v) {
    throw new Error(`Missing required env var: ${name}. Copy .env.example to .env and fill it in.`);
  }
  return v;
}

function optional(name, fallback) {
  const v = process.env[name];
  return v === undefined || v === '' ? fallback : v;
}

export const config = {
  env: optional('NODE_ENV', 'development'),
  port: Number(optional('PORT', '4000')),

  databaseUrl: optional('DATABASE_URL', 'file:./local.db'),
  databaseAuthToken: optional('DATABASE_AUTH_TOKEN', ''),

  jwtAccessSecret: required('JWT_ACCESS_SECRET'),
  jwtRefreshSecret: required('JWT_REFRESH_SECRET'),
  accessTtlSec: Number(optional('ACCESS_TTL_SEC', '900')),
  refreshTtlSec: Number(optional('REFRESH_TTL_SEC', String(60 * 60 * 24 * 30))),

  appBaseUrl: optional('APP_BASE_URL', 'http://localhost:4000'),
  memberAppUrl: optional('MEMBER_APP_URL', 'http://localhost:5173'),
  marketingBaseUrl: optional('MARKETING_BASE_URL', 'https://notebookofacoo.com'),

  stripe: {
    secretKey: optional('STRIPE_SECRET_KEY', ''),
    webhookSecret: optional('STRIPE_WEBHOOK_SECRET', ''),
    priceId: optional('STRIPE_PRICE_ID', ''),
  },

  resendApiKey: optional('RESEND_API_KEY', ''),
  fromEmail: optional('FROM_EMAIL', 'JT, Notebook of a COO <jt@notebookofacoo.com>'),
};

// True once the $10/mo price and secret key are configured.
export function stripeReady() {
  return Boolean(config.stripe.secretKey && config.stripe.priceId);
}
