import { beforeEach, describe, expect, it, vi } from 'vitest'

const cookieValues = vi.hoisted(() => new Map<string, string>())

vi.mock('next/headers', () => ({
  cookies: async () => ({
    get: (name: string) => {
      const value = cookieValues.get(name)
      return value === undefined ? undefined : { value }
    },
  }),
}))

import { getStorefrontLanguage } from './i18n.server'
import { MARKETPLACE_LANGUAGE_COOKIE, SHARED_LANGUAGE_COOKIE } from './i18n'

describe('getStorefrontLanguage', () => {
  beforeEach(() => {
    cookieValues.clear()
  })

  it('prefers the shared language cookie over the legacy storefront cookie', async () => {
    cookieValues.set(SHARED_LANGUAGE_COOKIE, 'ar')
    cookieValues.set(MARKETPLACE_LANGUAGE_COOKIE, 'fr')

    await expect(getStorefrontLanguage()).resolves.toBe('ar')
  })

  it('falls back to the legacy storefront cookie during migration', async () => {
    cookieValues.set(MARKETPLACE_LANGUAGE_COOKIE, 'fr')

    await expect(getStorefrontLanguage()).resolves.toBe('fr')
  })

  it('defaults to English when cookies are absent or invalid', async () => {
    await expect(getStorefrontLanguage()).resolves.toBe('en')
    cookieValues.set(SHARED_LANGUAGE_COOKIE, 'es')

    await expect(getStorefrontLanguage()).resolves.toBe('en')
  })
})
