import { z } from "zod";

const runtimeBoolean = (defaultValue: boolean) =>
  z
    .enum(["true", "false"])
    .default(defaultValue ? "true" : "false")
    .transform((value) => value === "true");

const browserHttpUrl = z
  .string()
  .url()
  .superRefine((value, context) => {
    const url = new URL(value);
    if (!["http:", "https:"].includes(url.protocol)) {
      context.addIssue({ code: z.ZodIssueCode.custom, message: "仅支持 HTTP(S) 地址" });
    }
    if (url.username || url.password) {
      context.addIssue({ code: z.ZodIssueCode.custom, message: "浏览器运行时地址不能包含凭据" });
    }
    if (url.hash) {
      context.addIssue({ code: z.ZodIssueCode.custom, message: "浏览器运行时地址不能包含片段" });
    }
  });

const runtimeConfigSchema = z.object({
  TJWATER_MAPBOX_ACCESS_TOKEN: z.string().default(""),
  TJWATER_MAP_URL: browserHttpUrl.default("https://geoserver.waternetwork.cn/geoserver"),
  TJWATER_GEOSERVER_WORKSPACE: z.string().trim().min(1).default("tjwater"),
  TJWATER_AGENT_API_BASE_URL: browserHttpUrl.default("http://127.0.0.1:8787"),
  TJWATER_ENABLE_DEV_PANEL: runtimeBoolean(false),
  TJWATER_ENABLE_MSW: runtimeBoolean(false)
});

declare global {
  var __TJWATER_CONFIG__: unknown;
}

export type RuntimeConfig = z.infer<typeof runtimeConfigSchema>;

export function parseRuntimeConfig(value: unknown): RuntimeConfig {
  return runtimeConfigSchema.parse(value ?? {});
}

export const env = parseRuntimeConfig(globalThis.__TJWATER_CONFIG__);
