// src/server/shared/lib/env.ts
// Centralized environment configuration for auth, CORS, and cookie settings

export const env = {
  get appEnv(): 'development' | 'production' {
    return process.env.APP_ENV === 'production' ? 'production' : 'development';
  },

  get isProduction(): boolean {
    return this.appEnv === 'production';
  },

  get isDev(): boolean {
    return this.appEnv === 'development';
  },

  get port(): number {
    return Number(process.env.PORT) || 3000;
  },

  get corsOrigin(): string | string[] {
    const origin = process.env.CORS_ORIGIN;
    if (!origin) return 'http://localhost:5173';
    return origin.split(',').map(o => o.trim());
  },

  get cookieSecure(): boolean {
    if (process.env.COOKIE_SECURE !== undefined) {
      return process.env.COOKIE_SECURE === 'true';
    }
    return this.isProduction;
  },

  get cookieSameSite(): 'lax' | 'none' | 'strict' {
    const val = process.env.COOKIE_SAMESITE?.toLowerCase();
    if (val === 'none' || val === 'lax' || val === 'strict') return val;
    return this.isProduction ? 'lax' : 'lax';
  },

  get trustProxy(): string | number | boolean {
    if (process.env.TRUST_PROXY !== undefined) {
      const v = process.env.TRUST_PROXY;
      if (v === 'true') return true;
      if (v === 'false') return false;
      if (/^\d+$/.test(v)) return Number(v);
      return v;
    }
    return this.isProduction;
  },

  get jwtSecret(): string {
    return process.env.JWT_SECRET || 'super-secret-key';
  },
} as const;

export type CookieOptions = {
  httpOnly: boolean;
  secure: boolean;
  sameSite: 'lax' | 'none' | 'strict';
  path: string;
  maxAge?: number;
  expires?: Date;
  domain?: string;
};

export function getAuthCookieOptions(overrides?: Partial<CookieOptions>): CookieOptions {
  return {
    httpOnly: true,
    secure: env.cookieSecure,
    sameSite: env.cookieSameSite,
    path: '/',
    maxAge: 60 * 60 * 24 * 7,
    ...overrides,
  };
}

export function getClearCookieOptions(): CookieOptions {
  return getAuthCookieOptions({
    expires: new Date(0),
  });
}
