import { decodeJwtPayload, isTokenNotValidError } from './jwtHelpers';
import {
  ACCESS_TOKEN_KEY,
  authorizationHeader,
  clearTokens,
  setTokens,
} from './tokenStorage';

describe('jwtHelpers', () => {
  it('decodeJwtPayload reads exp claim', () => {
    const payload = btoa(JSON.stringify({ exp: 1999999999 }));
    const token = `h.${payload}.s`;
    expect(decodeJwtPayload(token)).toEqual({ exp: 1999999999 });
  });

  it('decodeJwtPayload returns null for garbage', () => {
    expect(decodeJwtPayload('not-a-jwt')).toBeNull();
  });

  it('isTokenNotValidError detects SimpleJWT shape', () => {
    expect(
      isTokenNotValidError({
        response: { status: 401, data: { code: 'token_not_valid' } },
      }),
    ).toBe(true);
    expect(
      isTokenNotValidError({
        response: { status: 403, data: { code: 'token_not_valid' } },
      }),
    ).toBe(false);
  });
});

describe('JWT-only auth contract (#22)', () => {
  beforeEach(() => {
    localStorage.clear();
  });

  it('stores tokens without cookies and builds Authorization header', async () => {
    await setTokens('access-xyz', 'refresh-xyz');
    expect(document.cookie).not.toMatch(/csrftoken/);
    expect(authorizationHeader()).toBe('JWT access-xyz');
    await clearTokens();
    expect(localStorage.getItem(ACCESS_TOKEN_KEY)).toBeNull();
    expect(authorizationHeader()).toBeNull();
  });
});
