import * as fs from 'node:fs';
import * as path from 'node:path';
import { describe, expect, it, vi } from 'vitest';

import { TypeOrmAvatarRepository } from './TypeOrmAvatarRepository';

describe('TypeOrmAvatarRepository', () => {
  it('does not construct its own mapper dependencies', () => {
    const sourcePath = path.resolve(__dirname, 'TypeOrmAvatarRepository.ts');
    const source = fs.readFileSync(sourcePath, 'utf8');

    expect(source).not.toMatch(/new\s+AvatarOrmMapper\s*\(/);
    expect(source).not.toMatch(/=\s*new\s+AvatarOrmMapper\s*\(/);
  });

  it('requires mapper injection via constructor (no default mapper)', () => {
    expect(TypeOrmAvatarRepository.length).toBe(2);
  });

  it('uses the injected mapper at runtime (DB-free)', async () => {
    const ormRepo = {
      findOne: vi.fn().mockResolvedValue({ id: 'avatar-1' }),
      find: vi.fn().mockResolvedValue([{ id: 'avatar-1' }, { id: 'avatar-2' }]),
      save: vi.fn().mockResolvedValue({ id: 'avatar-1' }),
      delete: vi.fn().mockResolvedValue({ affected: 1 }),
    };

    const dataSource = {
      getRepository: vi.fn().mockReturnValue(ormRepo),
    };

    const mapper = {
      toStored: vi.fn().mockReturnValue({ id: 'stored-avatar-1' }),
      toDomain: vi.fn().mockReturnValue({ id: 'domain-avatar-1' }),
      toOrmEntity: vi.fn().mockReturnValue({ id: 'orm-avatar-1' }),
    };

    const repo = new TypeOrmAvatarRepository(dataSource as any, mapper as any);

    // Test findById
    const avatar = await repo.findById('avatar-1');
    expect(dataSource.getRepository).toHaveBeenCalledTimes(1);
    expect(ormRepo.findOne).toHaveBeenCalledWith({ where: { id: 'avatar-1' } });
    expect(mapper.toDomain).toHaveBeenCalledTimes(1);
    expect(avatar).toEqual({ id: 'domain-avatar-1' });

    // Test findActiveByDriverId
    await repo.findActiveByDriverId('driver-1');
    expect(ormRepo.findOne).toHaveBeenCalledWith({
      where: { driverId: 'driver-1', isActive: true },
      order: { selectedAt: 'DESC' }
    });

    // Test findByDriverId
    const avatars = await repo.findByDriverId('driver-1');
    expect(ormRepo.find).toHaveBeenCalledWith({
      where: { driverId: 'driver-1' },
      order: { selectedAt: 'DESC' }
    });
    expect(mapper.toDomain).toHaveBeenCalledTimes(4); // 1 from findById + 1 from findActiveByDriverId + 2 from findByDriverId
    expect(avatars).toHaveLength(2);

    // Test save
    const domainAvatar = { id: 'new-avatar', toProps: () => ({ id: 'new-avatar' }) };
    await repo.save(domainAvatar as any);
    expect(mapper.toOrmEntity).toHaveBeenCalledWith(domainAvatar);
    expect(ormRepo.save).toHaveBeenCalledWith({ id: 'orm-avatar-1' });

    // Test delete
    await repo.delete('avatar-1');
    expect(ormRepo.delete).toHaveBeenCalledWith({ id: 'avatar-1' });
  });
});
