export function buildSessionPayload(
  session: TencentBrowserSessionPayloadSource,
  {
    activityUrl = '',
    includeQrImage = true,
    sessionDebugEnabled = false,
    browserDebug = null,
  }: BuildSessionPayloadOptions = {},
): any {
  const activityInfo = session.lastState?.activityInfo || null
  const payload: Record<string, any> = {
    sessionId: session.sessionId,
    loginType: session.loginType,
    activityUrl,
    status: session.status,
    notice: session.notice,
    createdAt: session.createdAt,
    updatedAt: session.updatedAt,
    expiresAt: new Date(session.expiresAt).toISOString(),
    qrUpdatedAt: session.qrUpdatedAt,
    credentialReady: Boolean(session.lastState?.credentialReady),
    activityInfo,
    review: buildReviewPayload(session.lastReview),
    redeem: buildRedeemPayload(session.lastRedeem),
    artifacts: buildArtifactsPayload(session),
  }

  if (includeQrImage) {
    payload.qrImageBase64 = session.qrImageBase64
  }

  if (!sessionDebugEnabled) {
    return payload
  }

  return {
    ...payload,
    cookieKeys: Array.isArray(session.lastState?.cookieKeys) ? session.lastState.cookieKeys : [],
    state: session.lastState,
    browserDebug,
    qrImagePath: session.qrImagePath,
    review: buildReviewPayload(session.lastReview, { includeInternalPaths: true }),
    redeem: buildRedeemPayload(session.lastRedeem, { includeInternalPaths: true }),
    artifacts: buildArtifactsPayload(session, { includeInternalPaths: true }),
  }
}

type BuildSessionPayloadOptions = {
  activityUrl?: string
  includeQrImage?: boolean
  sessionDebugEnabled?: boolean
  browserDebug?: unknown
}

type InternalPathOptions = {
  includeInternalPaths?: boolean
}

type TencentBrowserSessionPayloadSource = {
  sessionId: string
  loginType?: string
  status?: string
  notice?: string
  createdAt?: string
  updatedAt?: string
  expiresAt: string | number | Date
  qrUpdatedAt?: string
  qrImageBase64?: string
  qrImagePath?: string
  sessionDir?: string
  lastState?: {
    credentialReady?: boolean
    cookieKeys?: string[]
    activityInfo?: any
    [key: string]: unknown
  } | null
  lastReview?: ReviewPayloadSource | null
  lastRedeem?: RedeemPayloadSource | null
}

type ReviewPayloadSource = {
  capturedAt?: string
  roleId?: string
  roleName?: string
  screenshotPath?: string
  signature?: string
}

type RedeemAttemptPayloadSource = {
  attempt?: number
  redeem?: unknown
}

type RedeemPayloadSource = {
  code?: string
  area?: string
  proofMode?: string
  attempts?: RedeemAttemptPayloadSource[]
  final?: RedeemAttemptPayloadSource | null
  finishedAt?: string
  screenshotPath?: string
  htmlPath?: string
  resultPath?: string
}

export function buildReviewPayload(review: ReviewPayloadSource | null | undefined, { includeInternalPaths = false }: InternalPathOptions = {}) {
  if (!review) {
    return null
  }

  const payload = {
    capturedAt: review.capturedAt,
    roleId: review.roleId || '',
    roleName: review.roleName || '',
  }

  if (!includeInternalPaths) {
    return payload
  }

  return {
    ...payload,
    screenshotPath: review.screenshotPath || '',
    signature: review.signature || '',
  }
}

export function buildRedeemPayload(redeem: RedeemPayloadSource | null | undefined, { includeInternalPaths = false }: InternalPathOptions = {}) {
  if (!redeem) {
    return null
  }

  const payload = {
    code: redeem.code,
    area: redeem.area,
    proofMode: redeem.proofMode || 'full',
    attempts: Array.isArray(redeem.attempts)
      ? redeem.attempts.map((attempt) => ({
          attempt: attempt.attempt,
          redeem: attempt.redeem || null,
        }))
      : [],
    final: redeem.final
      ? {
          attempt: redeem.final.attempt,
          redeem: redeem.final.redeem || null,
        }
      : null,
    finishedAt: redeem.finishedAt,
  }

  if (!includeInternalPaths) {
    return payload
  }

  return {
    ...payload,
    screenshotPath: redeem.screenshotPath || '',
    htmlPath: redeem.htmlPath || '',
    resultPath: redeem.resultPath || '',
  }
}

export function buildArtifactsPayload(
  session: Pick<
    TencentBrowserSessionPayloadSource,
    'sessionDir' | 'qrImagePath' | 'qrImageBase64' | 'lastReview' | 'lastRedeem'
  >,
  { includeInternalPaths = false }: InternalPathOptions = {},
) {
  const payload = {
    hasQrImage: Boolean(session.qrImageBase64),
    hasReviewScreenshot: Boolean(session.lastReview?.screenshotPath),
    hasScreenshot: Boolean(session.lastRedeem?.screenshotPath),
  }

  if (!includeInternalPaths) {
    return payload
  }

  return {
    ...payload,
    sessionDir: session.sessionDir,
    qrImagePath: session.qrImagePath,
    screenshotPath: session.lastRedeem?.screenshotPath || '',
    htmlPath: session.lastRedeem?.htmlPath || '',
    resultPath: session.lastRedeem?.resultPath || '',
    reviewScreenshotPath: session.lastReview?.screenshotPath || '',
  }
}
