import fs from 'node:fs/promises'

import { BAIDU_BEIJING_TIME_URL, type RedeemProofMode } from './session-proof-constants.js'

type RedeemResultFilePayload = {
  proofMode: RedeemProofMode
  sessionId?: string
  activityUrl: string
  code: string
  finalResult?: {
    role?: {
      area?: string
    }
    [key: string]: unknown
  } | null
  attempts?: unknown[]
  screenshotPath: string
  htmlPath?: string
  redeemPageScreenshotPath?: string
  beijingTimeScreenshotPath?: string
  beijingTimePageUrl?: string
  beijingTimeError?: string
}

export async function writeRedeemResultFile(
  resultPath: string,
  {
    proofMode,
    sessionId,
    activityUrl,
    code,
    finalResult,
    attempts,
    screenshotPath,
    htmlPath = '',
    redeemPageScreenshotPath = '',
    beijingTimeScreenshotPath = '',
    beijingTimePageUrl = BAIDU_BEIJING_TIME_URL,
    beijingTimeError = '',
  }: RedeemResultFilePayload,
): Promise<void> {
  await fs.writeFile(
    resultPath,
    JSON.stringify(
      {
        proofMode,
        sessionId,
        activityUrl,
        code,
        area: finalResult?.role?.area || '',
        final: finalResult,
        attempts,
        redeemPageScreenshotPath,
        beijingTimeScreenshotPath,
        beijingTimePageUrl,
        beijingTimeError,
        screenshotPath,
        htmlPath,
      },
      null,
      2,
    ),
    'utf8',
  )
}
