/** GeeLib SSO 登录与 Cookie 会话管理 */

const SSO_LOGIN_URL = 'https://login.ops.qihoo.net:4436/sec/login'
const GEELIB_DO_LOGIN_URL = 'https://geelib.qihoo.net/ones/Login/doLogin'
const GEELIB_VERIFY_URL =
  'https://geelib.qihoo.net/ones/user/userInfo?need_share=0'
const BOUNDARY = '----WebKitFormBoundaryGeelibCli'

let sessionCookie = ''

export function getCookie() {
  return sessionCookie
}

function buildFormData(fields) {
  let body = ''
  for (const [name, value] of Object.entries(fields)) {
    body += `--${BOUNDARY}\r\n`
    body += `Content-Disposition: form-data; name="${name}"\r\n\r\n`
    body += `${value}\r\n`
  }
  body += `--${BOUNDARY}--\r\n`
  return body
}

function parseCookies(headers) {
  const setCookies = headers.getSetCookie?.() ?? []
  const cookies = {}
  for (const c of setCookies) {
    const [pair] = c.split(';')
    const [name, ...rest] = pair.trim().split('=')
    cookies[name.trim()] = rest.join('=').trim()
  }
  return cookies
}

/** SSO 换取 sid */
async function ssoLogin(user, passwd) {
  const body = buildFormData({
    user,
    passwd,
    src: 'qihoo',
    syzm: '',
    ref: 'https://geelib.qihoo.net/geelib/',
  })

  const resp = await fetch(SSO_LOGIN_URL, {
    method: 'POST',
    headers: {
      'Content-Type': `multipart/form-data; boundary=${BOUNDARY}`,
      Accept: 'application/json, text/plain, */*',
      Cookie: 'SSO_PREFERED_DOMAIN=qihoo',
      Referer: 'https://login.ops.qihoo.net:4436/sec/login',
      'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    },
    body,
  })

  if (!resp.ok) {
    throw new Error(`SSO login failed: ${resp.status} ${resp.statusText}`)
  }
  const data = await resp.json()
  if (data.status !== 0) {
    throw new Error(`SSO login error: ${JSON.stringify(data)}`)
  }
  return data.sid
}

/** sid 换 GeeLib Cookie */
async function doLogin(sid) {
  const resp = await fetch(GEELIB_DO_LOGIN_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json, text/plain, */*',
      Referer: 'https://geelib.qihoo.net/geelib/',
      Origin: 'https://geelib.qihoo.net',
      'X-Requested-With': 'XMLHttpRequest',
      'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    },
    body: JSON.stringify({ sid, ref: 'https://geelib.qihoo.net/geelib/' }),
  })

  if (!resp.ok) {
    throw new Error(`doLogin failed: ${resp.status}`)
  }

  const cookies = parseCookies(resp.headers)
  const data = await resp.json()

  if (data.errno !== 2000) {
    throw new Error(`doLogin error: errno=${data.errno} errmsg=${data.errmsg}`)
  }

  const cookieStr = Object.entries(cookies)
    .map(([k, v]) => `${k}=${v}`)
    .join('; ')

  return {
    cookieStr,
    userName: data.data?.real_name ?? data.data?.name ?? '',
  }
}

async function verifyCookie(cookieStr) {
  try {
    const resp = await fetch(GEELIB_VERIFY_URL, {
      headers: {
        Cookie: cookieStr,
        Referer: 'https://geelib.qihoo.net/geelib/',
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        Accept: 'application/json, text/plain, */*',
        'X-Requested-With': 'XMLHttpRequest',
      },
    })
    const data = await resp.json()
    return data.errno === 2000
  } catch {
    return false
  }
}

/** 使用 GEELIB_USER / GEELIB_PASSWD 登录 */
export async function login() {
  const user = process.env.GEELIB_USER
  const passwd = process.env.GEELIB_PASSWD

  if (!user || !passwd) {
    throw new Error('请配置 GEELIB_USER 和 GEELIB_PASSWD 环境变量')
  }

  const sid = await ssoLogin(user, passwd)
  const { cookieStr } = await doLogin(sid)
  sessionCookie = cookieStr
  return cookieStr
}

/** Cookie 失效时自动重新登录 */
export async function ensureAuth() {
  if (sessionCookie && (await verifyCookie(sessionCookie))) {
    return
  }
  await login()
}
