import { z } from "zod";

/**
 * msg 服务环境变量 schema。
 *
 * 仲裁依据：
 * - G2 /readyz 多依赖检查（DB/ES/Redis/Kafka/PushGateway）
 * - M2 PushGateway 软失败（PUSH_GATEWAY_URL 可选）
 * - M4 HTTP POST /internal/push（豁免 gRPC）
 * - REDIS_URL 可选，未配置时降级到 DB 唯一索引去重
 */
const envSchema = z.object({
  PORT: z.string().default("3007"),
  GRPC_PORT: z.string().default("50056"),
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url().optional(),
  JWT_SECRET: z.string().optional(),
  JWT_ISSUER: z.string().default("next-edu-cloud"),
  KAFKA_BROKERS: z.string().default("localhost:9092"),
  KAFKA_CLIENT_ID: z.string().default("msg-service"),
  KAFKA_CONSUMER_GROUP_ID: z.string().default("msg-service-group"),
  ES_URL: z.string().url().optional(),
  PUSH_GATEWAY_URL: z.string().url().optional(),
  PUSH_INTERNAL_TOKEN: z.string().optional(),
  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();
