import { describe, expect, it } from 'vitest';
import { resolveCheckoutCsrfToken, resolvePaddleLocale } from '../steps/PaymentStep';

describe('resolvePaddleLocale', () => {
  it('returns short locale when given region-specific tag', () => {
    expect(resolvePaddleLocale('de-DE')).toBe('de');
    expect(resolvePaddleLocale('en-US')).toBe('en');
  });

  it('falls back to english when locale unsupported', () => {
    expect(resolvePaddleLocale('jp')).toBe('en');
    expect(resolvePaddleLocale('xx-YY')).toBe('en');
    expect(resolvePaddleLocale(undefined)).toBe('en');
  });

  it('keeps supported locale codes untouched', () => {
    expect(resolvePaddleLocale('fr')).toBe('fr');
    expect(resolvePaddleLocale('es')).toBe('es');
  });
});

describe('resolveCheckoutCsrfToken', () => {
  beforeEach(() => {
    document.head.innerHTML = '';
    document.cookie = 'XSRF-TOKEN=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
  });

  it('prefers the XSRF-TOKEN cookie when present', () => {
    const meta = document.createElement('meta');
    meta.setAttribute('name', 'csrf-token');
    meta.setAttribute('content', 'meta-token');
    document.head.appendChild(meta);

    document.cookie = 'XSRF-TOKEN=cookie-token';

    expect(resolveCheckoutCsrfToken()).toBe('cookie-token');
  });

  it('falls back to the meta csrf token when cookie is missing', () => {
    const meta = document.createElement('meta');
    meta.setAttribute('name', 'csrf-token');
    meta.setAttribute('content', 'meta-token');
    document.head.appendChild(meta);

    expect(resolveCheckoutCsrfToken()).toBe('meta-token');
  });
});
