import 'dotenv/config';
import { z } from 'zod';

/**
 * Centralized, validated environment config.
 * Fails fast at boot if anything required is missing or malformed,
 * so we never run with a half-configured server.
 */
const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'staging', 'production', 'test']).default('development'),
  PORT: z.coerce.number().int().positive().default(4000),
  CORS_ORIGIN: z.string().default('http://localhost:5173'),

  DATABASE_URL: z.string().min(1, 'DATABASE_URL is required'),

  JWT_ACCESS_SECRET: z.string().min(16, 'JWT_ACCESS_SECRET must be at least 16 chars'),
  JWT_REFRESH_SECRET: z.string().min(16, 'JWT_REFRESH_SECRET must be at least 16 chars'),
  JWT_ACCESS_EXPIRES_IN: z.string().default('15m'),
  JWT_REFRESH_EXPIRES_IN: z.string().default('7d'),
  BCRYPT_SALT_ROUNDS: z.coerce.number().int().min(4).max(15).default(12),
  REFRESH_COOKIE_NAME: z.string().default('hc_refresh'),
  // Open Super Admin bootstrap signup. Set to "false" once the platform's
  // Super Admin exists to hard-disable the /auth/signup endpoint, independent
  // of DB state. (z.coerce.boolean() treats any non-empty string as true, so we
  // parse the literal strings explicitly.)
  ALLOW_SUPER_ADMIN_SIGNUP: z
    .enum(['true', 'false'])
    .default('true')
    .transform((v) => v === 'true'),

  AWS_REGION: z.string().default('ap-south-1'),
  AWS_ACCESS_KEY_ID: z.string().optional(),
  AWS_SECRET_ACCESS_KEY: z.string().optional(),
  S3_BUCKET_NAME: z.string().optional(),
  UPLOAD_MAX_BYTES: z.coerce.number().int().positive().default(5_242_880),
  UPLOAD_ALLOWED_MIME: z.string().default('image/jpeg,image/png,application/pdf'),

  // Push notifications to the mobile app. "log" prints them and sends nothing.
  PUSH_PROVIDER: z.enum(['log', 'fcm']).default('log'),
  // The Firebase service-account key for PUSH_PROVIDER=fcm: the JSON itself,
  // or the same base64-encoded so it fits on one line.
  FIREBASE_SERVICE_ACCOUNT: z.string().optional(),
  // …or the path to that JSON file, so the key never has to be pasted anywhere.
  FIREBASE_SERVICE_ACCOUNT_FILE: z.string().optional(),

  // WhatsApp (rent reminders + notice broadcasts). Defaults to "log" (dry-run,
  // no real messages) until a real provider + credentials are configured.
  // Email. "log" is a dry run; "smtp" is any SMTP relay (we deploy with
  // Mailgun: smtp.mailgun.org, port 587 STARTTLS or 465 TLS, login = the
  // domain's SMTP credential); "resend" is Resend's HTTP API.
  EMAIL_PROVIDER: z.enum(['log', 'smtp', 'resend']).default('log'),
  EMAIL_API_KEY: z.string().optional(),
  EMAIL_FROM: z.string().optional(),
  EMAIL_REPLY_TO: z.string().optional(),
  SMTP_HOST: z.string().default('smtp.mailgun.org'),
  SMTP_PORT: z.coerce.number().int().positive().default(587),
  // true = TLS from the first byte (port 465); false = plain then STARTTLS (587).
  SMTP_SECURE: z
    .enum(['true', 'false'])
    .default('false')
    .transform((v) => v === 'true'),
  // Refuse to send in the clear when the relay does not offer STARTTLS.
  SMTP_REQUIRE_TLS: z
    .enum(['true', 'false'])
    .default('true')
    .transform((v) => v === 'true'),
  SMTP_USER: z.string().optional(),
  SMTP_PASS: z.string().optional(),
  // Two-step sign-in. Codes live for OTP_TTL_MINUTES. AUTH_OTP_ECHO returns
  // the code in the API response so automated tests can complete the flow
  // without a mailbox — it is refused outright in production (see below).
  OTP_TTL_MINUTES: z.coerce.number().int().min(2).max(30).default(10),
  /** Encrypts authenticator-app secrets at rest; unset = derived from JWT_REFRESH_SECRET. */
  TOTP_ENCRYPTION_KEY: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  AUTH_OTP_ECHO: z
    .enum(['true', 'false'])
    .default('false')
    .transform((v) => v === 'true'),
  // OpenAI, for the CRM's AI help. Unset (or empty) = AI features hidden.
  // OPENAI_BASE_URL exists so the smoke suite can stand in for OpenAI.
  OPENAI_API_KEY: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  OPENAI_MODEL: z.string().default('gpt-5.4'),
  OPENAI_BASE_URL: z.string().default('https://api.openai.com/v1'),
  OPENAI_TIMEOUT_MS: z.coerce.number().int().min(5000).max(120000).default(60000),
  /** US$ per million tokens, for the spend cap. GPT-5.4 list prices by default. */
  OPENAI_PRICE_INPUT_PER_M: z.coerce.number().min(0).default(2.5),
  OPENAI_PRICE_OUTPUT_PER_M: z.coerce.number().min(0).default(15),
  /** A stronger (or cheaper) model for the monthly insights report; empty = OPENAI_MODEL. */
  OPENAI_MODEL_REPORTS: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  /** Its prices; empty = the prices above. */
  OPENAI_REPORTS_PRICE_INPUT_PER_M: z.preprocess((v) => (v === '' ? undefined : v), z.coerce.number().min(0).optional()),
  OPENAI_REPORTS_PRICE_OUTPUT_PER_M: z.preprocess((v) => (v === '' ? undefined : v), z.coerce.number().min(0).optional()),
  // Lets the test suites move the CRM's clock (POST /api/crm/dev/tick) to
  // prove reminders fire once at the right time. Refused in production.
  CRM_TEST_CLOCK: z
    .enum(['true', 'false'])
    .default('false')
    .transform((v) => v === 'true'),
  // Online collection (Razorpay Payment Links + Route). Unset = feature
  // unavailable: the API says so and nothing is ever sent to a gateway.
  // RAZORPAY_BASE_URL exists so the smoke suite can stand in for Razorpay.
  RAZORPAY_KEY_ID: z.string().optional(),
  RAZORPAY_KEY_SECRET: z.string().optional(),
  RAZORPAY_WEBHOOK_SECRET: z.string().optional(),
  RAZORPAY_BASE_URL: z.string().default('https://api.razorpay.com'),
  RAZORPAY_ROUTE_REQUIRED: z
    .enum(['true', 'false'])
    .default('true')
    .transform((v) => v === 'true'),
  RAZORPAY_GATEWAY_FEE_PERCENT: z.coerce.number().min(0).max(10).default(2),
  RAZORPAY_GATEWAY_FEE_TAX_PERCENT: z.coerce.number().min(0).max(30).default(18),
  RAZORPAY_ROUTE_FEE_PERCENT: z.coerce.number().min(0).max(10).default(0.25),
  RAZORPAY_ROUTE_FEE_TAX_PERCENT: z.coerce.number().min(0).max(30).default(18),
  // Where a student lands after paying (display only). Defaults to the first CORS origin.
  // Razorpay's business category for a hostel's linked account.
  RAZORPAY_BUSINESS_CATEGORY: z.string().default('housing'),
  RAZORPAY_BUSINESS_SUBCATEGORY: z.string().default('facility_management'),
  PUBLIC_WEB_URL: z.string().optional(),
  PAYMENT_LINK_TTL_MINUTES: z.coerce.number().int().min(16).max(24 * 60).default(30),
  // Reconciliation (Sprint 3): the polling job can be switched off per process.
  DISABLE_COLLECTION_JOBS: z
    .enum(['true', 'false'])
    .default('false')
    .transform((v) => v === 'true'),
  WHATSAPP_PROVIDER: z.enum(['log', 'meta']).default('log'),
  // Sprint 5 (TEPL): SMS for emergency alerts. 'log' prints them; 'webhook'
  // POSTs { to, text } as JSON (bearer token) to the SMS gateway chosen later.
  SMS_PROVIDER: z.enum(['log', 'webhook']).default('log'),
  // Sprint 6 (TEPL): the key medical records are sealed with. Set it in production
  // (32+ random characters) and keep it safe: losing it loses the records.
  MEDICAL_ENCRYPTION_KEY: z.string().min(16).optional(),
  SMS_WEBHOOK_URL: z.string().url().optional(),
  SMS_WEBHOOK_TOKEN: z.string().optional(),
  // A Meta template for emergency alerts ({{1}} the title, {{2}} the message).
  WHATSAPP_TEMPLATE_EMERGENCY: z.string().optional(),
  // Meta-approved utility templates. When a name is set, business-initiated
  // messages go as that template (required outside the 24-hour window);
  // unset falls back to a plain text message, which Meta only delivers
  // inside an open conversation.
  WHATSAPP_TEMPLATE_LANG: z.string().default('en'),
  WHATSAPP_TEMPLATE_REMINDER: z.string().optional(),
  WHATSAPP_TEMPLATE_PAYMENT_LINK: z.string().optional(),
  // Lead automation (L1, 20 Oct 2026): Meta-approved utility templates for
  // the sales person's new-lead alert and the super admin's late-lead alert.
  // Unset = those alerts go by email only.
  WHATSAPP_TEMPLATE_LEAD_ALERT: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_TEMPLATE_LEAD_OVERDUE: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // Demo booking (L3): utility templates to the owner — confirmation, the
  // reminders, the recap after the demo and the "sorry we missed you".
  // Unset = those go by email only (and the booking page shows the details).
  WHATSAPP_TEMPLATE_DEMO_CONFIRM: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_TEMPLATE_DEMO_REMINDER: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_TEMPLATE_DEMO_RECAP: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_TEMPLATE_DEMO_NOSHOW: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // The marketing website, for links in owner emails (book again, change a booking).
  PUBLIC_SITE_URL: z.string().default('https://hostelcare.co.in'),
  // Sites whose forms may post leads to /api/public/leads (comma-separated).
  LEAD_FORM_ORIGINS: z.string().default('https://hostelcare.co.in,https://www.hostelcare.co.in,https://hostelcare.in,https://www.hostelcare.in'),
  WHATSAPP_API_BASE: z.string().default('https://graph.facebook.com/v21.0'),
  WHATSAPP_API_TOKEN: z.string().optional(),
  WHATSAPP_PHONE_NUMBER_ID: z.string().optional(),
  // Webhook (12 Oct 2026): the token typed into Meta's "Verify token" box, and
  // the app secret that signs every event. Unset = the webhook refuses.
  WHATSAPP_VERIFY_TOKEN: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_APP_SECRET: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // Meta lead ads (L4): the Page webhook at /api/webhooks/meta-leads. The
  // verify token typed into Meta, the app secret that signs events (blank =
  // WHATSAPP_APP_SECRET, when it is the same Meta app), and a long-lived Page
  // token with leads_retrieval to read each lead's answers.
  META_LEADS_VERIFY_TOKEN: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  META_APP_SECRET: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  META_PAGE_ACCESS_TOKEN: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // First touch (L4): the template every new lead gets ({{1}} first name,
  // {{2}} free-trial link, {{3}} demo booking link), and the one after a
  // second unanswered call ({{1}} first name, {{2}} demo booking link).
  WHATSAPP_TEMPLATE_LEAD_FIRST: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  WHATSAPP_TEMPLATE_LEAD_NO_ANSWER: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // Trial journey (L5): the nudge template ({{1}} first name, {{2}} the next
  // step, {{3}} app link), and where the day-30 email asks for a review.
  WHATSAPP_TEMPLATE_TRIAL_NUDGE: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  GOOGLE_REVIEW_URL: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // Nurture (L6): the one monthly marketing template ({{1}} first name, {{2}} the month's link).
  WHATSAPP_TEMPLATE_NURTURE: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  // Website blog CMS (docs/blog-cms-plan.md). Unset = the feed answers 503
  // and publishing waits (builds stay pending) until GitHub is configured.
  /** Shared with the website build (GitHub environment prod → secret BLOG_FEED_TOKEN). */
  BLOG_FEED_TOKEN: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined))
    .refine((v) => !v || v.length >= 32, 'BLOG_FEED_TOKEN must be at least 32 characters'),
  /** Fine-grained token: the website repository only, Actions read and write. */
  BLOG_GITHUB_TOKEN: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  BLOG_GITHUB_REPO: z.string().default('rajkumariparihar/hostelcare-website'),
  BLOG_GITHUB_WORKFLOW: z.string().default('deploy.yml'),
  BLOG_GITHUB_REF: z.string().default('deploy'),
  WEBSITE_URL: z.string().url().default('https://hostelcare.co.in'),
  /** "true" stops the publish job (scheduled posts and build tracking). */
  DISABLE_BLOG_PUBLISH_JOB: z
    .enum(['true', 'false'])
    .default('false')
    .transform((v) => v === 'true'),
  // Bug tracker (docs/bug-tracker-plan.md, BT6): GitHub tells us about commits
  // and pull requests that name a bug, at /api/webhooks/github. The secret is
  // the one typed into each repository's webhook; without it the endpoint
  // answers 503 and nothing is linked.
  BUG_GITHUB_WEBHOOK_SECRET: z
    .string()
    .optional()
    .transform((v) => (v && v.trim() ? v.trim() : undefined)),
  /** "owner/name,owner/name": only these repositories are listened to. Blank = any that knows the secret. */
  BUG_GITHUB_REPOS: z
    .string()
    .default('')
    .transform((v) => v.split(',').map((x) => x.trim().toLowerCase()).filter(Boolean)),
  /** A "Fixes BUG-n" commit counts as merged on these branches, and on the repository's default branch. */
  BUG_GITHUB_MERGED_BRANCHES: z
    .string()
    .default('main,master')
    .transform((v) => v.split(',').map((x) => x.trim()).filter(Boolean)),
});

const parsed = envSchema.safeParse(process.env);

if (!parsed.success) {
  // eslint-disable-next-line no-console
  console.error('❌ Invalid environment configuration:');
  // eslint-disable-next-line no-console
  console.error(parsed.error.flatten().fieldErrors);
  process.exit(1);
}

// Echoing sign-in codes would make two-step verification decorative. Never
// on a server people reach (production or staging — where a security test
// runs), whatever the env file says.
const deployed = parsed.data.NODE_ENV === 'production' || parsed.data.NODE_ENV === 'staging';
if (parsed.data.AUTH_OTP_ECHO && deployed) {
  // eslint-disable-next-line no-console
  console.error(`❌ AUTH_OTP_ECHO must not be enabled in ${parsed.data.NODE_ENV}.`);
  process.exit(1);
}
if (parsed.data.CRM_TEST_CLOCK && deployed) {
  // eslint-disable-next-line no-console
  console.error(`❌ CRM_TEST_CLOCK must not be enabled in ${parsed.data.NODE_ENV}.`);
  process.exit(1);
}
// Medical records fall back to a key derived from the refresh-token secret;
// rotating that secret would then make every record unreadable.
if (deployed && !parsed.data.MEDICAL_ENCRYPTION_KEY) {
  // eslint-disable-next-line no-console
  console.warn('⚠️  MEDICAL_ENCRYPTION_KEY is not set: medical records are sealed with a key derived from JWT_REFRESH_SECRET. Set it before real records go in, and never change it afterwards.');
}

export const env = parsed.data;
export const corsOrigins = env.CORS_ORIGIN.split(',').map((o) => o.trim());
export const leadFormOrigins = env.LEAD_FORM_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean);
export const publicWebUrl = (env.PUBLIC_WEB_URL ?? corsOrigins[0]).replace(/\/$/, '');
export const publicSiteUrl = env.PUBLIC_SITE_URL.replace(/\/$/, '');
export const uploadAllowedMime = env.UPLOAD_ALLOWED_MIME.split(',').map((m) => m.trim());
