import { type Plugin } from 'vite';

import { parseSessionIdleTimeoutMinutes } from '../lib/shared/session-idle';

interface EnvConfig {
  SITE_URL: string;
  BASE_PATH: string;
  MICROSOFT_AUTH_ENABLED: boolean;
  FILE_EVENTS_ENABLED: boolean;
  SENTRY_DSN?: string;
  SENTRY_TRACES_SAMPLE_RATE: number;
  TALE_VERSION?: string;
  SESSION_IDLE_TIMEOUT_MINUTES?: number;
}

function getEnvConfig(): EnvConfig {
  if (!process.env.SITE_URL) {
    throw new Error('Missing required environment variable: SITE_URL');
  }
  return {
    SITE_URL: process.env.SITE_URL,
    BASE_PATH: (process.env.BASE_PATH ?? '').replace(/\/$/, ''),
    MICROSOFT_AUTH_ENABLED: !!process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
    FILE_EVENTS_ENABLED: process.env.TALE_FILE_EVENTS === 'true',
    SENTRY_DSN: process.env.SENTRY_DSN,
    SENTRY_TRACES_SAMPLE_RATE: parseFloat(
      process.env.SENTRY_TRACES_SAMPLE_RATE || '1.0',
    ),
    TALE_VERSION: process.env.TALE_VERSION,
    SESSION_IDLE_TIMEOUT_MINUTES: parseSessionIdleTimeoutMinutes() ?? undefined,
  };
}

export function injectEnv(): Plugin {
  let envConfig: EnvConfig;
  let isProduction = false;

  return {
    name: 'inject-env',
    configResolved(config) {
      isProduction = config.command === 'build';
      if (!isProduction) {
        envConfig = getEnvConfig();
      }
    },
    transformIndexHtml: {
      order: 'pre',
      handler(html) {
        if (isProduction) {
          return html;
        }
        const envScript = `window.__ENV__ = ${JSON.stringify(envConfig)};`;
        return html.replace(
          /window\.__ENV__\s*=\s*['"]__ENV_PLACEHOLDER__['"];/,
          envScript,
        );
      },
    },
  };
}
