import dotenv from 'dotenv';
import path from 'path';

// Load from root .env (project-wide single source of truth).
// In Docker, env vars are already injected by docker-compose so this is a no-op.
dotenv.config({ path: path.resolve(__dirname, '../../../.env') });

interface EnvironmentConfig {
  nodeEnv: string;
  port: number;
  database: {
    host: string;
    port: number;
    name: string;
    user: string;
    password: string;
  };
  jwt: {
    secret: string;
    expiresIn: string | number;
  };
  cors: {
    origin: string;
  };
  rateLimit: {
    windowMs: number;
    max: number;
  };
  authentik: {
    issuer: string;
    clientId: string;
    clientSecret: string;
    redirectUri: string;
  };
  nextcloudUrl: string;
  bookstack: {
    url: string;
    tokenId: string;
    tokenSecret: string;
  };
  vikunja: {
    url: string;
    apiToken: string;
  };
}

const environment: EnvironmentConfig = {
  nodeEnv: process.env.NODE_ENV || 'development',
  port: parseInt(process.env.PORT || '3000', 10),
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5432', 10),
    name: process.env.DB_NAME || 'feuerwehr_dev',
    user: process.env.DB_USER || 'dev_user',
    password: process.env.DB_PASSWORD || 'dev_password',
  },
  jwt: {
    secret: process.env.JWT_SECRET || '',
    expiresIn: process.env.JWT_EXPIRES_IN || '24h',
  },
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:3001',
  },
  rateLimit: {
    windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000', 10), // 15 minutes
    max: parseInt(process.env.RATE_LIMIT_MAX || '300', 10),
  },
  authentik: {
    issuer: process.env.AUTHENTIK_ISSUER || 'https://auth.firesuite.feuerwehr-rems.at/application/o/feuerwehr-dashboard/',
    clientId: process.env.AUTHENTIK_CLIENT_ID || 'your_client_id_here',
    clientSecret: process.env.AUTHENTIK_CLIENT_SECRET || 'your_client_secret_here',
    redirectUri: process.env.AUTHENTIK_REDIRECT_URI || 'http://localhost:5173/auth/callback',
  },
  nextcloudUrl: process.env.NEXTCLOUD_URL || '',
  bookstack: {
    url: process.env.BOOKSTACK_URL || '',
    tokenId: process.env.BOOKSTACK_TOKEN_ID || '',
    tokenSecret: process.env.BOOKSTACK_TOKEN_SECRET || '',
  },
  vikunja: {
    url: process.env.VIKUNJA_URL || '',
    apiToken: process.env.VIKUNJA_API_TOKEN || '',
  },
};

function validateEnvironment(env: EnvironmentConfig): void {
  const secret = env.jwt.secret;

  if (!secret) {
    throw new Error(
      'FATAL: JWT_SECRET is not set. ' +
      'Set a strong, random secret of at least 32 characters before starting the server.'
    );
  }

  if (secret === 'your-secret-key-change-in-production') {
    throw new Error(
      'FATAL: JWT_SECRET is still set to the known weak default value. ' +
      'Replace it with a strong, random secret of at least 32 characters.'
    );
  }

  if (secret.length < 32) {
    throw new Error(
      `FATAL: JWT_SECRET is too short (${secret.length} characters). ` +
      'A minimum of 32 characters is required.'
    );
  }
}

validateEnvironment(environment);

export default environment;
