import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  _electron as electron,
  expect,
  test as base,
  type ElectronApplication,
  type Page,
} from '@playwright/test'

import { AppPage } from './pages/app.page.js'

const here = dirname(fileURLToPath(import.meta.url))
/** The built main-process entry Playwright launches. `yarn e2e` builds it first. */
const MAIN_ENTRY = join(here, '..', 'out', 'main', 'index.js')

interface CommiteaFixtures {
  /** The launched Electron application. */
  electronApp: ElectronApplication
  /** The app's first (and only) BrowserWindow, as a Playwright Page. */
  window: Page
  /** Page Object over the app shell. */
  app: AppPage
}

export const test = base.extend<CommiteaFixtures>({
  electronApp: async ({}, use) => {
    const electronApp = await electron.launch({
      args: [MAIN_ENTRY],
      env: { ...process.env, NODE_ENV: 'test', COMMITEA_E2E: '1' },
    })
    await use(electronApp)
    await electronApp.close()
  },

  window: async ({ electronApp }, use) => {
    const window = await electronApp.firstWindow()
    await window.waitForLoadState('domcontentloaded')
    await use(window)
  },

  app: async ({ window }, use) => {
    await use(new AppPage(window))
  },
})

export { expect }
