import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { GetProfileOverviewUseCase } from './GetProfileOverviewUseCase';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import { ISocialGraphRepository } from '@core/social/domain/repositories/ISocialGraphRepository';
import { IImageServicePort } from '../ports/IImageServicePort';
import { Driver } from '../../domain/entities/Driver';
import { Team } from '../../domain/entities/Team';

describe('GetProfileOverviewUseCase', () => {
  let useCase: GetProfileOverviewUseCase;
  let driverRepository: {
    findById: Mock;
  };
  let teamRepository: {
    findAll: Mock;
  };
  let teamMembershipRepository: {
    getMembership: Mock;
  };
  let socialRepository: {
    getFriends: Mock;
  };
  let imageService: {
    getDriverAvatar: Mock;
  };
  let getDriverStats: Mock;
  let getAllDriverRankings: Mock;

  beforeEach(() => {
    driverRepository = {
      findById: vi.fn(),
    };
    teamRepository = {
      findAll: vi.fn(),
    };
    teamMembershipRepository = {
      getMembership: vi.fn(),
    };
    socialRepository = {
      getFriends: vi.fn(),
    };
    imageService = {
      getDriverAvatar: vi.fn(),
    };
    getDriverStats = vi.fn();
    getAllDriverRankings = vi.fn();
    useCase = new GetProfileOverviewUseCase(
      driverRepository as unknown as IDriverRepository,
      teamRepository as unknown as ITeamRepository,
      teamMembershipRepository as unknown as ITeamMembershipRepository,
      socialRepository as unknown as ISocialGraphRepository,
      imageService as unknown as IImageServicePort,
      getDriverStats,
      getAllDriverRankings,
    );
  });

  it('should return profile overview for existing driver', async () => {
    const driverId = 'driver-1';
    const driver = Driver.create({
      id: driverId,
      iracingId: '123',
      name: 'Test Driver',
      country: 'US',
    });
    const teams = [Team.create({ id: 'team-1', name: 'Test Team', tag: 'TT', description: 'Test', ownerId: 'owner-1', leagues: [] })];
    const friends = [Driver.create({ id: 'friend-1', iracingId: '456', name: 'Friend', country: 'US' })];
    const statsAdapter = {
      rating: 1500,
      wins: 5,
      totalRaces: 10,
      avgFinish: 3.5,
    };
    const rankings = [{ driverId, rating: 1500, overallRank: 1 }];

    driverRepository.findById.mockResolvedValue(driver);
    teamRepository.findAll.mockResolvedValue(teams);
    teamMembershipRepository.getMembership.mockResolvedValue(null);
    socialRepository.getFriends.mockResolvedValue(friends);
    imageService.getDriverAvatar.mockReturnValue('avatar-url');
    getDriverStats.mockReturnValue(statsAdapter);
    getAllDriverRankings.mockReturnValue(rankings);

    const result = await useCase.execute({ driverId });

    expect(result.isOk()).toBe(true);
    const viewModel = result.unwrap();
    expect(viewModel.currentDriver?.id).toBe(driverId);
    expect(viewModel.extendedProfile).toBe(null);
  });

  it('should return error for non-existing driver', async () => {
    const driverId = 'driver-1';
    driverRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ driverId });

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'DRIVER_NOT_FOUND',
      message: 'Driver not found',
    });
  });

  it('should return error on repository failure', async () => {
    const driverId = 'driver-1';
    driverRepository.findById.mockRejectedValue(new Error('DB error'));

    const result = await useCase.execute({ driverId });

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'REPOSITORY_ERROR',
      message: 'Failed to fetch profile overview',
    });
  });
});