const Joi = require('joi');

const envSchema = Joi.object({
  NODE_ENV: Joi.string()
    .valid('development', 'test', 'production', 'dev_stage')
    .default('development'),

  PORT: Joi.number().default(8080),

  DB_HOST: Joi.string().default('localhost'),
  DB_PORT: Joi.number().default(5432),
  DB_NAME: Joi.string().default('db_tour_builder_platform'),
  DB_USER: Joi.string().default('postgres'),
  DB_PASS: Joi.string().allow('').default(''),

  SECRET_KEY: Joi.string()
    .min(16)
    .default('88dbeaf8-e906-405e-9e41-c3baadeda5c6'),

  ADMIN_PASS: Joi.string().default('88dbeaf8'),
  USER_PASS: Joi.string().default('c3baadeda5c6'),
  ADMIN_EMAIL: Joi.string().email().default('admin@flatlogic.com'),

  GOOGLE_CLIENT_ID: Joi.string().allow('').default(''),
  GOOGLE_CLIENT_SECRET: Joi.string().allow('').default(''),
  MS_CLIENT_ID: Joi.string().allow('').default(''),
  MS_CLIENT_SECRET: Joi.string().allow('').default(''),

  AWS_ACCESS_KEY_ID: Joi.string().allow('').default(''),
  AWS_SECRET_ACCESS_KEY: Joi.string().allow('').default(''),
  AWS_S3_BUCKET: Joi.string().allow('').default(''),
  AWS_S3_REGION: Joi.string().default('us-east-1'),
  AWS_S3_PREFIX: Joi.string().default('afeefb9d49f5b7977577876b99532ac7'),

  EMAIL_USER: Joi.string().allow('').default(''),
  EMAIL_PASS: Joi.string().allow('').default(''),
  EMAIL_TLS_REJECT_UNAUTHORIZED: Joi.string()
    .valid('true', 'false')
    .default('true'),

  GPT_KEY: Joi.string().allow('').default(''),
  PEXELS_KEY: Joi.string().allow('').default(''),

  LOG_LEVEL: Joi.string()
    .valid('fatal', 'error', 'warn', 'info', 'debug', 'trace')
    .default('info'),
}).unknown(true);

function validateEnv() {
  const { error, value } = envSchema.validate(process.env, {
    abortEarly: false,
    stripUnknown: false,
  });

  if (error) {
    const messages = error.details.map((d) => `  - ${d.message}`).join('\n');
    console.error('Environment validation failed:\n' + messages);

    if (process.env.NODE_ENV === 'production') {
      process.exit(1);
    } else {
      console.warn('Continuing with default values in non-production mode');
    }
  }

  return value;
}

module.exports = { validateEnv, envSchema };
