const WECHAT_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";

export type WechatAuthConfig = {
  appId: string;
  redirectUri: string;
  scope: "snsapi_base" | "snsapi_userinfo";
  state: string;
};

export function getWechatAuthConfig(): WechatAuthConfig | null {
  const appId = process.env.NEXT_PUBLIC_WECHAT_APP_ID;
  const redirectUri =
    process.env.NEXT_PUBLIC_WECHAT_AUTH_REDIRECT_URI ||
    (typeof window !== "undefined" ? `${window.location.origin}/h5` : "");
  const scope = (process.env.NEXT_PUBLIC_WECHAT_AUTH_SCOPE || "snsapi_userinfo") as WechatAuthConfig["scope"];

  if (!appId || !redirectUri) {
    return null;
  }

  return {
    appId,
    redirectUri,
    scope,
    state: "hyqa_h5"
  };
}

export function buildWechatOAuthUrl(config: WechatAuthConfig): string {
  const params = new URLSearchParams({
    appid: config.appId,
    redirect_uri: config.redirectUri,
    response_type: "code",
    scope: config.scope,
    state: config.state
  });

  return `${WECHAT_OAUTH_URL}?${params.toString()}#wechat_redirect`;
}

export function isWechatBrowser(userAgent: string): boolean {
  return /MicroMessenger/i.test(userAgent);
}
