import { existsSync, mkdirSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { execSync } from 'node:child_process'

const projectRoot = join(dirname(fileURLToPath(import.meta.url)), '../../..')
const devCertsDir = join(projectRoot, '.dev-certs')
const devKey = join(devCertsDir, 'key.pem')
const devCert = join(devCertsDir, 'cert.pem')

const { getDb } = await import('../../server/utils/db.js')
const { hashPassword } = await import('../../server/utils/password.js')
const { TEST_ADMIN } = await import('./fixtures/users.js')

const ensureDevCerts = () => {
  if (existsSync(devKey) && existsSync(devCert)) return

  mkdirSync(devCertsDir, { recursive: true })
  try {
    execSync(
      `openssl req -x509 -newkey rsa:2048 -keyout "${devKey}" -out "${devCert}" -days 365 -nodes -subj "/CN=localhost" -addext "subjectAltName=IP:127.0.0.1,DNS:localhost"`,
      { cwd: projectRoot, stdio: process.env.CI ? 'pipe' : 'inherit' },
    )
  }
  catch (error) {
    throw new Error(`Failed to generate dev certificates: ${error.message}`, { cause: error })
  }
}

export default async function globalSetup() {
  ensureDevCerts()

  let retries = 3
  while (retries > 0) {
    try {
      const { get, run } = await getDb()
      const existing = await get('SELECT id FROM users WHERE identifier = ?', [TEST_ADMIN.identifier])

      if (!existing) {
        await run(
          'INSERT INTO users (id, identifier, password_hash, role, created_at, auth_provider, oidc_issuer, oidc_sub) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          [crypto.randomUUID(), TEST_ADMIN.identifier, hashPassword(TEST_ADMIN.password), TEST_ADMIN.role, new Date().toISOString(), 'local', null, null],
        )
      }
      return
    }
    catch (error) {
      if (error.message?.includes('SQLITE_BUSY') || error.message?.includes('database is locked')) {
        retries--
        if (retries > 0) {
          await new Promise(resolve => setTimeout(resolve, 100 * (4 - retries)))
          continue
        }
      }
      throw error
    }
  }
}
