import { describe, it, expect } from 'vitest';
import { SignJWT } from 'jose';
import { createSession, verifySession, verifyPassword } from '../../src/lib/auth';

describe('verifyPassword', () => {
  it('accepte le mot de passe correct', async () => {
    expect(await verifyPassword('test-password-123')).toBe(true);
  });

  it('rejette un mauvais mot de passe', async () => {
    expect(await verifyPassword('wrong')).toBe(false);
  });

  it('rejette un mot de passe vide', async () => {
    expect(await verifyPassword('')).toBe(false);
  });
});

describe('verifySession', () => {
  it('rejette un token undefined', async () => {
    expect(await verifySession(undefined)).toBe(false);
  });

  it('rejette un token vide', async () => {
    expect(await verifySession('')).toBe(false);
  });

  it('rejette un token mal formé', async () => {
    expect(await verifySession('not.a.jwt')).toBe(false);
  });

  it('rejette un JWT signé avec un autre secret', async () => {
    const otherKey = new TextEncoder().encode('different-secret-of-32-chars-min-aaaa');
    const token = await new SignJWT({ role: 'admin' })
      .setProtectedHeader({ alg: 'HS256' })
      .setIssuedAt()
      .setExpirationTime('7d')
      .sign(otherKey);
    expect(await verifySession(token)).toBe(false);
  });

  it('round-trip : createSession puis verifySession → true', async () => {
    const token = await createSession();
    expect(token).toMatch(/^eyJ/);
    expect(await verifySession(token)).toBe(true);
  });
});
