export interface AppEnvironment {
  databaseUrl: string;
  redisUrl: string;
  appVersion: string;
  teamCityBuildNumber: string;
  sourceRevision: string;
}

function required(env: NodeJS.ProcessEnv, name: string): string {
  const value = env[name]?.trim();
  if (!value) throw new Error(`Missing required environment variable: ${name}`);
  return value;
}

export function loadEnvironment(env: NodeJS.ProcessEnv): AppEnvironment {
  return {
    databaseUrl: required(env, 'DATABASE_URL'),
    redisUrl: required(env, 'REDIS_URL'),
    appVersion: env.APP_VERSION?.trim() || 'dev',
    teamCityBuildNumber: env.TEAMCITY_BUILD_NUMBER?.trim() || 'local',
    sourceRevision: env.SOURCE_REVISION?.trim() || 'local',
  };
}

export const APP_ENVIRONMENT = Symbol('APP_ENVIRONMENT');

export const appEnvironmentProvider = {
  provide: APP_ENVIRONMENT,
  useFactory: () => loadEnvironment(process.env),
};
