/// <reference lib="dom" />

import {
  BAIDU_BEIJING_TIME_URL,
  BEIJING_TIME_PROOF_CLIP,
  BEIJING_TIME_PROOF_VIEWPORT,
} from './session-proof-constants.js'

type BrowserPageLike = {
  setViewportSize: (viewport: { width: number; height: number }) => Promise<void>
  goto: (url: string, options?: { waitUntil?: string }) => Promise<unknown>
  waitForTimeout: (milliseconds: number) => Promise<void>
  evaluate: (callback: () => unknown) => Promise<unknown>
  screenshot: (options: {
    path: string
    clip: { x: number; y: number; width: number; height: number }
  }) => Promise<unknown>
  close: () => Promise<void>
}

type BrowserContextLike = {
  newPage: () => Promise<BrowserPageLike>
}

export type BeijingTimeProof = {
  screenshotPath: string
  pageUrl: string
}

export async function captureBeijingTimeProof(
  browserContext: BrowserContextLike,
  { screenshotPath }: { screenshotPath: string },
): Promise<BeijingTimeProof> {
  const proofPage = await browserContext.newPage()

  try {
    await proofPage.setViewportSize(BEIJING_TIME_PROOF_VIEWPORT)
    await proofPage.goto(BAIDU_BEIJING_TIME_URL, { waitUntil: 'domcontentloaded' })
    await proofPage.waitForTimeout(3_000)
    await proofPage.evaluate(() => {
      window.scrollTo(0, 0)
    })
    await proofPage.screenshot({
      path: screenshotPath,
      clip: BEIJING_TIME_PROOF_CLIP,
    })

    return {
      screenshotPath,
      pageUrl: BAIDU_BEIJING_TIME_URL,
    }
  } finally {
    await proofPage.close().catch(() => null)
  }
}
