import 'dotenv/config';
import * as joi from 'joi';

interface EnvVars {
  HOST_API: string;
  ALLOW_CORS_URL: string;
  PORT: number;
  NODE_ENV: string;
  DATABASE_URL: string;
  ACCESS_TOKEN_SECRET: string;
  ACCESS_TOKEN_EXPIRATION: string;
  REFRESH_TOKEN_SECRET: string;
  REFRESH_TOKEN_EXPIRATION: string;
  MAIL_HOST: string;
  MAIL_USERNAME: string;
  MAIL_PASSWORD: string;
  MINIO_ENDPOINT: string;
  MINIO_PORT: number;
  MINIO_ACCESS_KEY: string;
  MINIO_SECRET_KEY: string;
  MINIO_BUCKET: string;
  MINIO_USE_SSL: boolean;
}

const envsSchema = joi
  .object({
    HOST_API: joi.string().required(),
    ALLOW_CORS_URL: joi.string().required(),
    PORT: joi.number().required(),
    NODE_ENV: joi.string().required(),
    DATABASE_URL: joi.string().required(),
    ACCESS_TOKEN_SECRET: joi.string().required(),
    ACCESS_TOKEN_EXPIRATION: joi.string().required(),
    REFRESH_TOKEN_SECRET: joi.string().required(),
    REFRESH_TOKEN_EXPIRATION: joi.string().required(),
    MAIL_HOST: joi.string(),
    MAIL_USERNAME: joi.string(),
    MAIL_PASSWORD: joi.string(),
    MINIO_ENDPOINT: joi.string().required(),
    MINIO_PORT: joi.number().required(),
    MINIO_ACCESS_KEY: joi.string().required(),
    MINIO_SECRET_KEY: joi.string().required(),
    MINIO_BUCKET: joi.string().required(),
    MINIO_USE_SSL: joi.boolean().default(false),
  })
  .unknown(true);

const { error, value } = envsSchema.validate(process.env);

if (error) {
  throw new Error(`Config validation error: ${error.message}`);
}

const envVars: EnvVars = value;

export const envs = {
  port: envVars.PORT,
  dataBaseUrl: envVars.DATABASE_URL,
  node_env: envVars.NODE_ENV,
  host_api: envVars.HOST_API,
  allow_cors_url: envVars.ALLOW_CORS_URL,
  access_token_secret: envVars.ACCESS_TOKEN_SECRET,
  access_token_expiration: envVars.ACCESS_TOKEN_EXPIRATION,
  refresh_token_secret: envVars.REFRESH_TOKEN_SECRET,
  refresh_token_expiration: envVars.REFRESH_TOKEN_EXPIRATION,
  mail_host: envVars.MAIL_HOST,
  mail_username: envVars.MAIL_USERNAME,
  mail_password: envVars.MAIL_PASSWORD,
  minio_endpoint: envVars.MINIO_ENDPOINT,
  minio_port: envVars.MINIO_PORT,
  minio_access_key: envVars.MINIO_ACCESS_KEY,
  minio_secret_key: envVars.MINIO_SECRET_KEY,
  minio_bucket: envVars.MINIO_BUCKET,
  minio_use_ssl: envVars.MINIO_USE_SSL,
};
