import 'dotenv/config';
import ms from 'ms';
import type { StringValue } from 'ms';

export type AppEnv = 'development' | 'test' | 'production';

/** Value accepted by jsonwebtoken / @nestjs/jwt `signOptions.expiresIn`. */
export type JwtExpiresIn = number | StringValue;

export type AppConfig = {
  nodeEnv: AppEnv;
  databaseUrl: string;
  jwtSecret: string;
  jwtExpiresIn: JwtExpiresIn;
  port: number;
  host: string;
  frontendUrl: string;
  allowPublicRegistration: boolean;
  bcryptRounds: number;
};

const DEFAULTS = {
  jwtExpiresIn: '1d' satisfies StringValue,
  port: 3000,
  host: '127.0.0.1',
  frontendUrl: 'http://127.0.0.1:5173',
  allowPublicRegistration: false,
  bcryptRounds: 10,
  minJwtSecretLength: 32,
} as const;

function parseBoolean(value: string | undefined, fallback: boolean): boolean {
  if (value === undefined || value.trim() === '') {
    return fallback;
  }

  const normalized = value.trim().toLowerCase();
  if (['1', 'true', 'yes', 'on'].includes(normalized)) {
    return true;
  }
  if (['0', 'false', 'no', 'off'].includes(normalized)) {
    return false;
  }

  throw new Error(
    `Invalid boolean value "${value}". Expected true/false.`,
  );
}

function parsePort(value: string | undefined, fallback: number): number {
  if (value === undefined || value.trim() === '') {
    return fallback;
  }

  const port = Number(value);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new Error(`Invalid PORT "${value}". Expected an integer 1-65535.`);
  }

  return port;
}

function parseBcryptRounds(value: string | undefined, fallback: number): number {
  if (value === undefined || value.trim() === '') {
    return fallback;
  }

  const rounds = Number(value);
  if (!Number.isInteger(rounds) || rounds < 4 || rounds > 15) {
    throw new Error(
      `Invalid BCRYPT_ROUNDS "${value}". Expected an integer 4-15.`,
    );
  }

  return rounds;
}

function parseNodeEnv(value: string | undefined): AppEnv {
  const normalized = (value ?? 'development').trim().toLowerCase();
  if (
    normalized === 'development' ||
    normalized === 'test' ||
    normalized === 'production'
  ) {
    return normalized;
  }

  throw new Error(
    `Invalid NODE_ENV "${value}". Expected development, test, or production.`,
  );
}

function requireNonEmpty(name: string, value: string | undefined): string {
  if (!value || value.trim() === '') {
    throw new Error(`${name} environment variable is required`);
  }
  return value.trim();
}

function stripWrappingQuotes(value: string): string {
  if (
    (value.startsWith('"') && value.endsWith('"')) ||
    (value.startsWith("'") && value.endsWith("'"))
  ) {
    return value.slice(1, -1).trim();
  }
  return value;
}

/**
 * Parses JWT_EXPIRES_IN into a jsonwebtoken-compatible expiresIn value.
 * Pure integers are treated as seconds; other values must be ms timespans.
 */
export function parseJwtExpiresIn(
  value: string | undefined,
  fallback: StringValue = DEFAULTS.jwtExpiresIn,
): JwtExpiresIn {
  const source = value === undefined || value.trim() === '' ? fallback : value.trim();
  const raw = stripWrappingQuotes(source);

  if (!raw) {
    throw new Error(
      'Invalid JWT_EXPIRES_IN. Expected a positive number of seconds or timespan (e.g. "1d", "20h", 60).',
    );
  }

  if (/^\d+$/.test(raw)) {
    const seconds = Number(raw);
    if (!Number.isSafeInteger(seconds) || seconds <= 0) {
      throw new Error(
        `Invalid JWT_EXPIRES_IN "${value}". Expected a positive number of seconds or timespan (e.g. "1d", "20h", 60).`,
      );
    }
    return seconds;
  }

  const milliseconds = ms(raw as StringValue);
  if (
    typeof milliseconds !== 'number' ||
    !Number.isFinite(milliseconds) ||
    milliseconds <= 0
  ) {
    throw new Error(
      `Invalid JWT_EXPIRES_IN "${value}". Expected a positive number of seconds or timespan (e.g. "1d", "20h", 60).`,
    );
  }

  return raw as StringValue;
}

/**
 * Loads and validates application configuration from process.env.
 * Never logs secret values.
 */
export function loadAppConfig(
  env: NodeJS.ProcessEnv = process.env,
): AppConfig {
  const nodeEnv = parseNodeEnv(env['NODE_ENV']);
  const databaseUrl = requireNonEmpty('DATABASE_URL', env['DATABASE_URL']);
  const jwtSecret = requireNonEmpty('JWT_SECRET', env['JWT_SECRET']);

  if (jwtSecret.length < DEFAULTS.minJwtSecretLength) {
    throw new Error(
      `JWT_SECRET must be at least ${DEFAULTS.minJwtSecretLength} characters`,
    );
  }

  const jwtExpiresIn = parseJwtExpiresIn(env['JWT_EXPIRES_IN']);
  const port = parsePort(env['PORT'], DEFAULTS.port);
  const host = env['HOST']?.trim() || DEFAULTS.host;
  const frontendUrl = env['FRONTEND_URL']?.trim() || DEFAULTS.frontendUrl;
  const allowPublicRegistration = parseBoolean(
    env['ALLOW_PUBLIC_REGISTRATION'],
    DEFAULTS.allowPublicRegistration,
  );
  const bcryptRounds = parseBcryptRounds(
    env['BCRYPT_ROUNDS'],
    DEFAULTS.bcryptRounds,
  );

  return {
    nodeEnv,
    databaseUrl,
    jwtSecret,
    jwtExpiresIn,
    port,
    host,
    frontendUrl,
    allowPublicRegistration,
    bcryptRounds,
  };
}

export const APP_CONFIG = Symbol('APP_CONFIG');
