import { z } from "zod";

const envSchema = z.object({
  PORT: z.string().default("3005"),
  GRPC_PORT: z.string().default("50054"),
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url().optional(),
  NEO4J_URL: z.string().url().optional(),
  NEO4J_PASSWORD: z.string().optional(),
  ES_URL: z.string().url().optional(),
  KAFKA_BROKERS: z.string().default("localhost:9092"),
  JWT_SECRET: z.string().optional(),
  JWT_ISSUER: z.string().default("next-edu-cloud"),
  OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url().optional(),
  LOG_LEVEL: z
    .enum(["fatal", "error", "warn", "info", "debug", "trace"])
    .default("info"),
  NODE_ENV: z
    .enum(["development", "production", "test"])
    .default("development"),
  DEV_MODE: z.string().optional().default("false"),
});

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

export function loadEnv(): Env {
  const result = envSchema.safeParse(process.env);
  if (!result.success) {
    console.error(
      "❌ Invalid environment variables:",
      result.error.flatten().fieldErrors,
    );
    throw new Error("Invalid environment configuration");
  }
  return result.data;
}

export const env = loadEnv();
