import { getLoginTypeLabel, type LoginType } from './session-browser-config.js'

export const SESSION_TTL_MS = 30 * 60 * 1000

type InitialQrSessionStateOptions = {
  updatedAt?: string
  nowMs?: number
  sessionTtlMs?: number
  loginTypeLabel?: string
}

type HostState = {
  loginText?: string
  unloginVisible?: boolean
  loginedVisible?: boolean
}

type QrState = {
  expired?: boolean
  scanned?: boolean
}

type ActivityInfo = {
  role?: {
    ready?: boolean
    roleName?: string
  }
}

type SessionStatusInput = {
  hostState: HostState
  qrState: QrState
  credentialReady?: boolean
  activityInfo?: ActivityInfo | null
}

type SessionNoticeInput = SessionStatusInput & {
  loginType: LoginType | string
}

type CookieMap = {
  openid?: string
  access_token?: string
  appid?: string
}

export function resolveInitialQrSessionState(
  loginType: LoginType | string,
  {
    updatedAt = new Date().toISOString(),
    nowMs = Date.now(),
    sessionTtlMs = SESSION_TTL_MS,
    loginTypeLabel = getLoginTypeLabel(loginType),
  }: InitialQrSessionStateOptions = {},
) {
  return {
    status: 'waiting_scan',
    notice: `请使用${loginTypeLabel}扫码登录`,
    updatedAt,
    expiresAt: nowMs + sessionTtlMs,
  }
}

export function resolveTencentSessionExpiresAt(
  session: { autoCloseAt?: number | string } | null | undefined,
  nowMs = Date.now(),
  sessionTtlMs = SESSION_TTL_MS,
): number {
  const autoCloseAt = Number(session?.autoCloseAt || 0)
  if (autoCloseAt > 0) {
    return autoCloseAt
  }

  return nowMs + sessionTtlMs
}

export function shouldRefreshLoggedInPresentation(hostState: HostState): boolean {
  const loginText = String(hostState?.loginText || '').trim()

  return Boolean(hostState?.unloginVisible || !hostState?.loginedVisible || !loginText)
}

export function resolveSessionStatus({ hostState, qrState, credentialReady, activityInfo }: SessionStatusInput): string {
  if (hostState.loginedVisible || credentialReady) {
    if (credentialReady && activityInfo?.role?.ready) {
      return 'ready_to_redeem'
    }

    return 'logged_in'
  }

  if (qrState.expired) {
    return 'expired'
  }

  if (qrState.scanned) {
    return 'scanned'
  }

  return 'waiting_scan'
}

export function resolveSessionNotice({
  hostState,
  qrState,
  credentialReady,
  activityInfo,
  loginType,
}: SessionNoticeInput): string {
  const loginTypeLabel = getLoginTypeLabel(loginType)

  if (credentialReady) {
    if (activityInfo?.role?.ready && activityInfo.role.roleName) {
      return `登录已完成，当前角色 ${activityInfo.role.roleName}`
    }

    return '登录已完成，正在同步角色信息'
  }

  if (hostState.loginedVisible) {
    return '页面已识别登录态'
  }

  if (qrState.expired) {
    return '二维码已失效，准备刷新'
  }

  if (qrState.scanned) {
    return '二维码已扫描，请在手机上确认登录'
  }

  return `请使用${loginTypeLabel}扫码登录`
}

export function hasRedeemCredential(cookieMap: CookieMap): boolean {
  return Boolean(cookieMap.openid && cookieMap.access_token && cookieMap.appid)
}
