import { expect, test as setup } from "@playwright/test"
import path from "path"
import fs from "fs"

/**
 * Global setup — authenticates as admin and saves the session state
 * so all authenticated tests can reuse it without logging in again.
 *
 * Runs as a Playwright "setup project" that other projects depend on.
 */

const authDir = path.join(__dirname, ".auth")
const authFile = path.join(authDir, "admin.json")

setup("authenticate as admin", async ({ page, context }) => {
  const baseURL = "http://localhost:3000"

  // Ensure .auth directory exists
  if (!fs.existsSync(authDir)) {
    fs.mkdirSync(authDir, { recursive: true })
  }

  // Navigate to login page
  await page.goto(`${baseURL}/login`)
  await page.waitForLoadState("domcontentloaded")

  // Fill credentials and submit
  await page.fill('input[name="email"], input[type="email"]', "admin@test.de")
  await page.fill(
    'input[name="password"], input[type="password"]',
    "test123"
  )
  await page.click('button[type="submit"]')

  // Wait for successful redirect away from login
  await page.waitForURL((url) => !url.pathname.includes("/login"), {
    timeout: 15000,
  })

  // Wait for session cookies to settle
  await page.waitForLoadState("domcontentloaded")
  await page.waitForTimeout(1000)

  // Verify we're authenticated (sanity check)
  const url = page.url()
  expect(url).not.toContain("/login")

  // Save the authenticated state (cookies + localStorage)
  await context.storageState({ path: authFile })
})
