import {
  describe,
  it,
  expect
} from 'vitest';
import crypto from 'crypto';
import {
  hashPasswordForStorage,
  isLegacySha256Hash,
  verifyPassword
} from './password-auth.service';

describe('password-auth.service', () => {
  it('stores bcrypt hashes for new passwords', async () => {
    const hash = await hashPasswordForStorage('secret-pass');

    expect(hash.startsWith('$2')).toBe(true);
    expect(isLegacySha256Hash(hash)).toBe(false);
  });

  it('verifies bcrypt passwords', async () => {
    const hash = await hashPasswordForStorage('secret-pass');

    await expect(verifyPassword('secret-pass', hash)).resolves.toBe(true);
    await expect(verifyPassword('wrong-pass', hash)).resolves.toBe(false);
  });

  it('verifies legacy sha256 passwords', async () => {
    const legacyHash = crypto.createHash('sha256').update('legacy-pass')
      .digest('hex');

    expect(isLegacySha256Hash(legacyHash)).toBe(true);
    await expect(verifyPassword('legacy-pass', legacyHash)).resolves.toBe(true);
    await expect(verifyPassword('wrong-pass', legacyHash)).resolves.toBe(false);
  });

  it('rehashes legacy passwords to bcrypt after successful verification', async () => {
    const legacyHash = crypto.createHash('sha256').update('legacy-pass')
      .digest('hex');
    const upgraded = await hashPasswordForStorage('legacy-pass', legacyHash);

    expect(upgraded.startsWith('$2')).toBe(true);
    await expect(verifyPassword('legacy-pass', upgraded)).resolves.toBe(true);
  });
});
