import fs from 'node:fs/promises'
import path from 'path'

const root = path.join('test', 'screenshots')

export function takeScreenshotPlugin() {
  return {
    name: 'take-screen-command',

    async executeCommand({ command, payload, session }) {
      if (command === 'take-screenshot') {
        await fs.mkdir(root, { recursive: true })
        const config = /** @type {{ name: string }} */ (payload)

        const file = `${config.name}.png`
        const filePath = path.join(root, file)

        if (session.browser.type === 'puppeteer') {
          const page = session.browser.getPage(session.id)
          const screenshot = await page.screenshot()
          await fs.writeFile(filePath, screenshot)
          return true
        }
        if (session.browser.type === 'playwright') {
          const page = session.browser.getPage(session.id)
          const screenshot = await page.screenshot()
          await fs.writeFile(filePath, screenshot)
          return true
        }
        throw new Error(`Taking screenshots is not supported for browser type ${session.browser.type}.`)
      }
      return undefined
    },
  }
}
