import { AvatarGenerationRequest } from '@core/media/domain/entities/AvatarGenerationRequest';
import type { Logger } from '@core/shared/domain/Logger';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { InMemoryAvatarGenerationRepository } from './InMemoryAvatarGenerationRepository';

describe('InMemoryAvatarGenerationRepository', () => {
  let repository: InMemoryAvatarGenerationRepository;
  let mockLogger: Logger;

  beforeEach(() => {
    mockLogger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    repository = new InMemoryAvatarGenerationRepository(mockLogger);
  });

  it('saves and finds latest by user', async () => {
    const base1 = AvatarGenerationRequest.create({
      id: 'req-1',
      userId: 'user-1',
      facePhotoUrl: 'https://example.com/face1.png',
      suitColor: 'red',
    });

    const base2 = AvatarGenerationRequest.create({
      id: 'req-2',
      userId: 'user-1',
      facePhotoUrl: 'https://example.com/face2.png',
      suitColor: 'blue',
    });

    const r1Props = base1.toProps();
    const r2Props = base2.toProps();

    const r1 = AvatarGenerationRequest.reconstitute(r1Props);
    const r2 = AvatarGenerationRequest.reconstitute({
      ...r2Props,
      createdAt: new Date(r1Props.createdAt.getTime() + 1000),
      updatedAt: new Date(r1Props.updatedAt.getTime() + 1000),
    });

    await repository.save(r1);
    await repository.save(r2);

    expect((await repository.findById('req-1'))?.id).toBe('req-1');
    expect((await repository.findByUserId('user-1')).length).toBe(2);

    const latest = await repository.findLatestByUserId('user-1');
    expect(latest?.id).toBe('req-2');
  });

  it('deletes requests', async () => {
    const r = AvatarGenerationRequest.create({
      id: 'req-del',
      userId: 'user-del',
      facePhotoUrl: 'https://example.com/face.png',
      suitColor: 'green',
    });

    await repository.save(r);
    await repository.delete('req-del');

    expect(await repository.findById('req-del')).toBeNull();
  });
});
