import { TestInfo } from '@playwright/test'

import { TEST_CONFIG } from 'playwright.config'

export type BackendScope = 'global' | 'file'
export async function startBackend(scope: BackendScope, testInfo: TestInfo): Promise<void> {
  if (scope === 'global') {
    return
  }
  console.log(`Starting backend for scope ${scope} in test ${testInfo.title} in file ${testInfo.file}`)
  try {
    await fetch(`${TEST_CONFIG.apiURL}/startBackend`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', ...getTestHeaders(testInfo) },
    })
  } catch (e) {
    console.error(`Failed to start backend on ${TEST_CONFIG.apiURL}`, e)
    throw e
  }
}

export async function stopBackend(scope: BackendScope, testInfo: TestInfo): Promise<void> {
  console.log(`Stopping backend for scope ${scope} in test ${testInfo.title} in file ${testInfo.file}`)
  await fetch(`${TEST_CONFIG.apiURL}/stopBackend`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', ...getTestHeaders(testInfo) },
  })
}

export function getTestHeaders(testInfo: TestInfo): Record<string, string> {
  return {
    'x-test-spec-file': testInfo.file,
    'x-test-test-title': testInfo.title,
  }
}
