import Cookies from 'js-cookie';
import { getApiUrl } from 'config/http';

export const GAdminTokenName = 'gadmin-token';

export function getUrlParams(search = window.location.search) {
  const hashes = search.slice(search.indexOf('?') + 1).split('&');
  return hashes.reduce(
    (acc, hash) => {
      const [key, val] = hash.split('=');
      if (val) acc[key] = decodeURIComponent(val);
      return acc;
    },
    {} as Record<string, string>,
  );
}

type LoginCookie = {
  gadminToken?: string;
};

// ─── 认证 / 会话 ──────────────────────────────────────────────────────────────

export function login() {
  clearLoginCookie();
  const apiUrl = getApiUrl();
  window.location.href = `${apiUrl}/login?redirect_url=${encodeURIComponent(
    window.location.href,
  )}`;
}

export function logout() {
  clearLoginCookie();
  const apiUrl = getApiUrl();
  window.location.href = `${apiUrl}/logout?redirect_url=${encodeURIComponent(
    window.location.origin,
  )}`;
}

/**
 * 通过cookie检测是否登录及参数转cookie(for dev)
 */
export function checkLogin(): boolean {
  // 优先处理 URL 参数中的 token，确保 token 被写入 cookie（任何域名下都需要）
  const params = getUrlParams();
  const gadminToken = params[GAdminTokenName];
  if (gadminToken) {
    setLoginCookie({ gadminToken });
    return true;
  }

  if (Cookies.get(GAdminTokenName)) {
    return true;
  }

  return false;
}

export function setLoginCookie({ gadminToken }: Required<LoginCookie>) {
  const expires = 1; // 本地登录态缓存1天
  Cookies.set(GAdminTokenName, gadminToken, { expires });
}

export function clearLoginCookie() {
  Cookies.remove(GAdminTokenName);
}

export function requestHeaders() {
  const gadminToken = Cookies.get(GAdminTokenName);
  const business = JSON.parse(Cookies.get('Business') || '{}');
  return {
    'X-Requested-With': 'XMLHttpRequest',
    // 防止 business.name 含中文等非 ASCII 字符导致 HTTP header 500
    ...(Object.keys(business).length > 0 && {
      'X-Gadmin-Business': JSON.stringify({
        ...business,
        name: encodeURIComponent(business.name),
      }),
    }),
    ...(gadminToken && { [GAdminTokenName]: gadminToken }),
  };
}
