import { expect, test as setup } from '@playwright/test'
import { mkdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

type TokenResponse = {
  access_token: string
  refresh_token: string
  token_type: string
}

const frontendOrigin = new URL(
  process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:4173',
).origin
const apiOrigin = process.env.PLAYWRIGHT_API_ORIGIN || 'http://127.0.0.1:8000'
const testEmail =
  process.env.PLAYWRIGHT_TEST_EMAIL || 'teamadmin@resolutionflow.example.com'
const testPassword =
  process.env.PLAYWRIGHT_TEST_PASSWORD || 'TestPass123!'

const authDir = fileURLToPath(new URL('./.auth/', import.meta.url))
const authFile = path.join(authDir, 'team-admin.json')

setup('authenticate seeded team admin and persist storage state', async ({ request }) => {
  const response = await request.post(`${apiOrigin}/api/v1/auth/login/json`, {
    data: {
      email: testEmail,
      password: testPassword,
    },
  })

  expect(response.ok()).toBeTruthy()

  const token = (await response.json()) as TokenResponse

  const authStorage = JSON.stringify({
    state: {
      token,
      isAuthenticated: true,
      account: null,
      subscription: null,
    },
    version: 0,
  })

  await mkdir(authDir, { recursive: true })
  await writeFile(
    authFile,
    JSON.stringify(
      {
        cookies: [],
        origins: [
          {
            origin: frontendOrigin,
            localStorage: [
              { name: 'access_token', value: token.access_token },
              { name: 'refresh_token', value: token.refresh_token },
              { name: 'auth-storage', value: authStorage },
            ],
          },
        ],
      },
      null,
      2,
    ),
    'utf8',
  )
})
