import { describe, it, expect, beforeAll } from 'vitest';
import { signToken, verifyToken } from './jwt.js';

beforeAll(() => {
  process.env.JWT_SECRET = 'test-secret-key-at-least-32-characters-long!!';
});

describe('signToken', () => {
  it('returns a non-empty string', async () => {
    const token = await signToken({ userId: 'u1', username: 'test', role: 'user' });
    expect(token).toBeTypeOf('string');
    expect(token.length).toBeGreaterThan(20);
  });
});

describe('verifyToken', () => {
  it('returns payload for valid token', async () => {
    const payload = { userId: 'abc', username: 'testuser', role: 'user' };
    const token = await signToken(payload);
    const result = await verifyToken(token);
    expect(result).not.toBeNull();
    expect(result.userId).toBe('abc');
    expect(result.username).toBe('testuser');
    expect(result.role).toBe('user');
  });

  it('returns null for invalid token', async () => {
    const result = await verifyToken('not.a.real.jwt.token');
    expect(result).toBeNull();
  });

  it('returns null for empty string', async () => {
    const result = await verifyToken('');
    expect(result).toBeNull();
  });

  it('returns null for null/undefined', async () => {
    const result = await verifyToken(null);
    expect(result).toBeNull();
  });

  it('roundtrip preserves all payload fields', async () => {
    const original = { userId: 'x1', username: 'jdoe', role: 'admin', extra: 'data' };
    const token = await signToken(original);
    const result = await verifyToken(token);
    expect(result.userId).toBe('x1');
    expect(result.username).toBe('jdoe');
    expect(result.role).toBe('admin');
  });
});
