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('; ')
      },
    },
  })
  Object.defineProperty(globalThis, 'atob', {
    configurable: true,
    value: (value: string) => Buffer.from(value, 'base64').toString('binary'),
  })
  return { store, get cookie() { return cookieValue } }
}

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

describe('storefront scoped preferences', () => {
  it('returns unscoped keys when no usable token exists', () => {
    installBrowser()
    expect(getScopedPreferenceKey('rentaldrivego-language')).toBe('rentaldrivego-language')
    expect(getScopedPreferenceCookieName('rentaldrivego-language')).toBe('rentaldrivego-language')
  })

  it('reads shared cookies before legacy local-storage fallbacks', () => {
    const browser = installBrowser('rentaldrivego-language=fr')
    browser.store.set('storefront-language', 'ar')

    expect(readScopedPreference('rentaldrivego-language', ['storefront-language'])).toBe('fr')
  })

  it('writes shared and legacy values without auth-token scoping', () => {
    const browser = installBrowser()

    writeScopedPreference('rentaldrivego-theme', 'dark', ['dashboard-theme'])

    expect(browser.store.get('rentaldrivego-theme')).toBe('dark')
    expect(browser.store.get('dashboard-theme')).toBe('dark')
    expect(browser.cookie).toContain('rentaldrivego-theme=dark')
  })
})
