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

import { TypeOrmMediaRepository } from './TypeOrmMediaRepository';

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

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

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

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

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

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

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

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

    // Test findByUploadedBy
    const medias = await repo.findByUploadedBy('user-1');
    expect(ormRepo.find).toHaveBeenCalledWith({ where: { uploadedBy: 'user-1' } });
    expect(mapper.toDomain).toHaveBeenCalledTimes(3); // 1 from findById + 2 from findByUploadedBy
    expect(medias).toHaveLength(2);

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

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