const TENCENT_COOKIE_URLS = [
  'https://df.qq.com',
  'https://ssl.captcha.qq.com',
  'https://graph.qq.com',
  'https://milo.qq.com',
]

type BrowserCookie = {
  name?: string
  value?: string
}

type BrowserContextLike = {
  cookies: (urls?: string[]) => Promise<BrowserCookie[]>
}

export type TencentCookieMap = Record<string, string>

export function normalizeTencentCookieMap(cookies: BrowserCookie[] = []): TencentCookieMap {
  const cookieMap: TencentCookieMap = {}

  for (const cookie of cookies) {
    if (!cookie?.name) {
      continue
    }

    cookieMap[String(cookie.name)] = String(cookie.value || '')
  }

  if (!cookieMap.acctype) {
    cookieMap.acctype = 'qc'
  }

  if (!cookieMap.appid) {
    cookieMap.appid = '101491592'
  }

  if (cookieMap.openid && cookieMap.access_token && !cookieMap.iegams_milo_proxylogin_qc) {
    cookieMap.iegams_milo_proxylogin_qc =
      `${cookieMap.appid}_$$_${cookieMap.openid}_$$_${cookieMap.access_token}`
  }

  return cookieMap
}

export async function loadCookieMapFromContext(browserContext: BrowserContextLike): Promise<TencentCookieMap> {
  const cookies = await browserContext.cookies(TENCENT_COOKIE_URLS)
  return normalizeTencentCookieMap(cookies)
}
