import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { setThemeCookie } from '../src/lib/theme-cookie'

function readRepoFile(relativePath: string): string {
  return readFileSync(resolve(__dirname, '../../..', relativePath), 'utf8')
}

describe('dark-light-theme contract', () => {
  it('emits a readable theme cookie for the boot script', () => {
    const headers = new Headers()
    const context = {
      header(name: string, value: string, options?: { append?: boolean }) {
        if (options?.append) {
          headers.append(name, value)
          return
        }
        headers.set(name, value)
      },
    } as never

    setThemeCookie(context, 'system')

    const cookie = headers.get('set-cookie')
    expect(cookie).toContain('ui_theme=system')
    expect(cookie).toContain('SameSite=Strict')
    expect(cookie).toContain('Secure')
    expect(cookie).not.toContain('HttpOnly')
  })

  it('threads a CSP nonce through the Astro base layout boot script', () => {
    const middleware = readRepoFile('apps/zync-www/src/middleware.ts')
    const baseLayout = readRepoFile('apps/zync-www/src/layouts/BaseLayout.astro')

    expect(middleware).toContain('locals.nonce')
    expect(middleware).toContain("'nonce-${nonce}'")
    expect(baseLayout).toContain('nonce={Astro.locals.nonce}')
  })
})
