import { z } from "zod";

const envSchema = z.object({
  PORT: z.string().default("3003"),
  IamServiceUrl: z.string().url().default("http://localhost:3002"),
  ClassesServiceUrl: z.string().url().default("http://localhost:3001"),
  CoreEduServiceUrl: z.string().url().default("http://localhost:3004"),
  OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url().optional(),
  LOG_LEVEL: z.string().default("info"),
  NODE_ENV: z.string().default("development"),
});

export type Env = z.infer<typeof envSchema>;

export function loadEnv(): Env {
  const result = envSchema.safeParse({
    ...process.env,
    IamServiceUrl: process.env.IAM_SERVICE_URL || "http://localhost:3002",
    ClassesServiceUrl:
      process.env.CLASSES_SERVICE_URL || "http://localhost:3001",
    CoreEduServiceUrl:
      process.env.CORE_EDU_SERVICE_URL || "http://localhost:3004",
  });
  if (!result.success) {
    throw new Error("Invalid env: " + JSON.stringify(result.error.flatten()));
  }
  return result.data;
}

export const env = loadEnv();
