import type { DataSource } from 'typeorm';
import { describe, expect, it, vi } from 'vitest';

import { TypeOrmUserRatingRepository } from './TypeOrmUserRatingRepository';

describe('TypeOrmUserRatingRepository', () => {
  it('constructor works with injected dependencies', () => {
    const dataSource = {} as unknown as DataSource;
    const repo = new TypeOrmUserRatingRepository(dataSource);
    expect(repo).toBeInstanceOf(TypeOrmUserRatingRepository);
  });

  it('findByUserId: returns null when not found', async () => {
    const findOne = vi.fn().mockResolvedValue(null);
    const dataSource = {
      getRepository: vi.fn().mockReturnValue({ findOne }),
    } as unknown as DataSource;

    const repo = new TypeOrmUserRatingRepository(dataSource);
    const result = await repo.findByUserId('user-1');

    expect(result).toBeNull();
    expect(findOne).toHaveBeenCalledWith({ where: { userId: 'user-1' } });
  });

  it('save: works with mocked TypeORM', async () => {
    const save = vi.fn().mockResolvedValue({});
    const dataSource = {
      getRepository: vi.fn().mockReturnValue({ save }),
    } as unknown as DataSource;

    const repo = new TypeOrmUserRatingRepository(dataSource);
    
    const mockRating = {
      userId: 'user-1',
      driver: { value: 50, confidence: 0, sampleSize: 0, trend: 'stable', lastUpdated: new Date() },
      admin: { value: 50, confidence: 0, sampleSize: 0, trend: 'stable', lastUpdated: new Date() },
      steward: { value: 50, confidence: 0, sampleSize: 0, trend: 'stable', lastUpdated: new Date() },
      trust: { value: 50, confidence: 0, sampleSize: 0, trend: 'stable', lastUpdated: new Date() },
      fairness: { value: 50, confidence: 0, sampleSize: 0, trend: 'stable', lastUpdated: new Date() },
      overallReputation: 50,
      createdAt: new Date(),
      updatedAt: new Date(),
    } as any;

    const result = await repo.save(mockRating);
    expect(result).toBe(mockRating);
    expect(save).toHaveBeenCalled();
  });
});