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

import { TypeOrmUserRepository } from './TypeOrmUserRepository';
import { UserOrmEntity } from '../entities/UserOrmEntity';
import { UserOrmMapper } from '../mappers/UserOrmMapper';

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

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

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

  it('uses the injected mapper at runtime (DB-free)', async () => {
    const ormRepo = {
      findOne: vi.fn().mockResolvedValue({ id: 'u1' }),
    } as unknown as Repository<UserOrmEntity>;

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

    const mapper = {
      toStored: vi.fn().mockReturnValue({ id: 'stored-u1' }),
      toOrmEntity: vi.fn(),
    } as unknown as UserOrmMapper;

    const repo = new TypeOrmUserRepository(dataSource, mapper);

    const user = await repo.findByEmail('ALICE@EXAMPLE.COM');

    expect(dataSource.getRepository).toHaveBeenCalledTimes(1);
    expect(ormRepo.findOne).toHaveBeenCalledTimes(1);
    expect(mapper.toStored).toHaveBeenCalledTimes(1);
    expect(user).toEqual({ id: 'stored-u1' });
  });
});