const AUTH_COOKIE_NAME = "Authorization"
const COOKIE_PATHS = ["/", "/screen2", "/screen2/"]

function getCookieDomainCandidates() {
  const hostname = window.location.hostname
  if (!hostname || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) return hostname ? [hostname] : []
  const parts = hostname.split(".").filter(Boolean)
  const domains = new Set([hostname, `.${hostname}`])
  if (parts.length > 2) {
    const parentDomain = parts.slice(-2).join(".")
    domains.add(parentDomain)
    domains.add(`.${parentDomain}`)
  }
  return Array.from(domains)
}

function encodeRedirect(path) {
  return encodeURIComponent(path || "/platform")
}

export function getAuthorizationToken() {
  const cookie = document.cookie
    .split(";")
    .map((item) => item.trim())
    .find((item) => item.startsWith(`${AUTH_COOKIE_NAME}=`))
  return cookie ? decodeURIComponent(cookie.slice(AUTH_COOKIE_NAME.length + 1)) : ""
}

export function clearAuthorizationToken() {
  const domains = getCookieDomainCandidates()
  COOKIE_PATHS.forEach((path) => {
    document.cookie = `${AUTH_COOKIE_NAME}=; Max-Age=0; path=${path}`
    document.cookie = `${AUTH_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`
    domains.forEach((domain) => {
      document.cookie = `${AUTH_COOKIE_NAME}=; Max-Age=0; path=${path}; domain=${domain}`
      document.cookie = `${AUTH_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}; domain=${domain}`
    })
  })
}

export function getLoginPath(redirect = window.location.hash.replace(/^#/, "") || "/platform") {
  return `/login?redirect=${encodeRedirect(redirect)}`
}

export function redirectToLogin(redirect) {
  clearAuthorizationToken()
  const loginPath = getLoginPath(redirect)
  if (window.location.hash.replace(/^#/, "") !== loginPath) {
    window.location.hash = loginPath
  }
}

export async function login(username, password) {
  clearAuthorizationToken()
  const response = await fetch("/login", {
    method: "POST",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      "Content-Language": "zh_CN",
    },
    body: JSON.stringify({ username, password }),
  })
  const data = await response.json().catch(() => ({}))
  if (!response.ok || data?.code !== 200) {
    const error = new Error(data?.msg || "登录失败，请检查用户名或密码。")
    error.status = response.status
    error.code = data?.code
    throw error
  }
  if (data?.data?.token) {
    document.cookie = `${AUTH_COOKIE_NAME}=${encodeURIComponent(data.data.token)}; path=/`
  }
  return data
}

export async function logout() {
  await fetch("/logout", {
    method: "POST",
    credentials: "include",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "Content-Language": "zh_CN",
    },
    body: "{}",
  }).catch(() => null)
  redirectToLogin("/platform")
}

export async function fetchCurrentUser() {
  const response = await fetch("/getInfo", {
    credentials: "include",
    headers: {
      Accept: "application/json",
      "Content-Language": "zh_CN",
    },
  })
  const data = await response.json().catch(() => ({}))
  if (!response.ok || data?.code !== 200) {
    const error = new Error(data?.msg || "用户未登录或授权已过期。")
    error.status = response.status || 401
    error.code = data?.code || 401
    throw error
  }
  return data.data
}
