import 'dotenv/config';

export type EnvLike = Record<string, string | undefined>;

export class Config {
  public readonly env: EnvLike;

  public readonly openAiKey: string;
  public readonly chatModel: string;
  public readonly embedModel: string;
  public readonly mongoUri: string;
  public readonly port: number;

  constructor(env: EnvLike = process.env as EnvLike) {
    this.env = env;

    this.openAiKey = env.OPEN_AI_KEY ?? '';
    this.chatModel = env.CHAT_MODEL ?? 'gpt-4o-mini';
    this.embedModel = env.EMBED_MODEL ?? 'text-embedding-3-small';
    this.mongoUri = env.MONGODB_URI ?? '';
    this.port = Number(env.PORT ?? 3000);
  }

  validate = (): this => {
    const missing: string[] = [];
    if (!this.openAiKey) missing.push('OPEN_AI_KEY');
    if (!this.mongoUri) missing.push('MONGODB_URI');

    if (missing.length) {
      throw new Error(`Missing env vars: ${missing.join(', ')}`);
    }

    if (!Number.isFinite(this.port) || this.port <= 0) {
      throw new Error(`Invalid PORT: ${this.port}`);
    }

    return this;
  };
}
