import { afterEach, describe, expect, it } from 'vitest'
import { getScopedPreferenceCookieName, getScopedPreferenceKey, readScopedPreference, writeScopedPreference } from './preferences'

function installBrowser(cookie = '') {
  const store = new Map<string, string>()
  let cookieValue = cookie
  Object.defineProperty(globalThis, 'window', {
    configurable: true,
    value: { localStorage: { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => store.set(key, value) } },
  })
  Object.defineProperty(globalThis, 'document', {
    configurable: true,
    value: {
      get cookie() { return cookieValue },
      set cookie(value: string) {
        const [pair] = value.split(';')
        const [name, val] = pair.split('=')
        cookieValue = cookieValue.split(';').map((chunk) => chunk.trim()).filter(Boolean).filter((chunk) => !chunk.startsWith(`${name}=`)).concat(`${name}=${val}`).join('; ')
      },
    },
  })
  return { store, get cookie() { return cookieValue } }
}

afterEach(() => {
  Reflect.deleteProperty(globalThis, 'window')
  Reflect.deleteProperty(globalThis, 'document')
})

describe('Carplace preferences', () => {
  it('uses the shared preference keys', () => {
    installBrowser()
    expect(getScopedPreferenceKey('rentaldrivego-language')).toBe('rentaldrivego-language')
    expect(getScopedPreferenceCookieName('rentaldrivego-language')).toBe('rentaldrivego-language')
  })

  it('prefers the shared cookie over local storage', () => {
    const browser = installBrowser('rentaldrivego-language=fr')
    browser.store.set('rentaldrivego-language', 'ar')
    expect(readScopedPreference('rentaldrivego-language')).toBe('fr')
  })

  it('writes one shared value to storage and cookies', () => {
    const browser = installBrowser()
    writeScopedPreference('rentaldrivego-theme', 'dark')
    expect(browser.store.get('rentaldrivego-theme')).toBe('dark')
    expect(browser.cookie).toContain('rentaldrivego-theme=dark')
  })
})
