import { z } from "zod";

const envSchema = z.object({
  // HTTP
  PORT: z.string().default("3002"),

  // Database
  DATABASE_URL: z.string().url(),

  // Redis（缓存 + token 黑名单）
  REDIS_URL: z.string().url(),

  // JWT RS256（president §2.15：本地文件密钥）
  IAM_PRIVATE_KEY_PATH: z.string(),
  IAM_PUBLIC_KEY_PATH: z.string(),
  JWT_ISSUER: z.string().default("next-edu-cloud"),
  JWT_AUDIENCE: z.string().default("next-edu-cloud"),
  JWT_KEY_ID: z.string().default("iam-rs256-v1"),
  ACCESS_TOKEN_TTL: z.string().default("15m"),
  REFRESH_TOKEN_TTL_DAYS: z.string().default("7"),

  // Kafka（Outbox 投递）
  KAFKA_BROKERS: z.string(),
  KAFKA_CLIENT_ID: z.string().default("iam-service"),

  // gRPC server（I1 裁决：端口 50052）
  GRPC_PORT: z.string().default("50052"),

  // 可观测性
  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"),
});

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();
