import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { Driver } from '../../domain/entities/Driver';
import { League } from '../../domain/entities/League';
import { LeagueMembership } from '../../domain/entities/LeagueMembership';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import {
    GetLeagueMembershipsUseCase,
    type GetLeagueMembershipsErrorCode,
    type GetLeagueMembershipsInput,
} from './GetLeagueMembershipsUseCase';

describe('GetLeagueMembershipsUseCase', () => {
  let useCase: GetLeagueMembershipsUseCase;
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let leagueRepository: {
    findById: Mock;
  };

  beforeEach(() => {
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    leagueRepository = {
      findById: vi.fn(),
    };
    useCase = new GetLeagueMembershipsUseCase(
      leagueMembershipRepository as unknown as LeagueMembershipRepository,
      driverRepository as unknown as DriverRepository,
      leagueRepository as unknown as LeagueRepository
    );
  });

  it('should return league memberships with drivers', async () => {
    const leagueId = 'league-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'Test Description',
      ownerId: 'owner-1',
    });
    const memberships = [
      LeagueMembership.create({
        id: 'membership-1',
        leagueId,
        driverId: 'driver-1',
        role: 'member',
        joinedAt: new Date(),
      }),
      LeagueMembership.create({
        id: 'membership-2',
        leagueId,
        driverId: 'driver-2',
        role: 'admin',
        joinedAt: new Date(),
      }),
    ];
    const driver1 = Driver.create({
      id: 'driver-1',
      iracingId: '123',
      name: 'Driver 1',
      country: 'US',
    });
    const driver2 = Driver.create({
      id: 'driver-2',
      iracingId: '456',
      name: 'Driver 2',
      country: 'UK',
    });

    leagueRepository.findById.mockResolvedValue(league);
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    driverRepository.findById.mockImplementation((id: string) => {
      if (id === 'driver-1') return Promise.resolve(driver1);
      if (id === 'driver-2') return Promise.resolve(driver2);
      return Promise.resolve(null);
    });

    const result = await useCase.execute({ leagueId } as GetLeagueMembershipsInput);

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();

    expect(presented.league).toEqual(league);
    expect(presented.memberships).toHaveLength(2);
    expect(presented.memberships[0]?.membership).toEqual(memberships[0]);
    expect(presented.memberships[0]?.driver).toEqual(driver1);
    expect(presented.memberships[1]?.membership).toEqual(memberships[1]);
    expect(presented.memberships[1]?.driver).toEqual(driver2);
  });

  it('should handle drivers not found', async () => {
    const leagueId = 'league-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'Test Description',
      ownerId: 'owner-1',
    });
    const memberships = [
      LeagueMembership.create({
        id: 'membership-1',
        leagueId,
        driverId: 'driver-1',
        role: 'member',
        joinedAt: new Date(),
      }),
    ];

    leagueRepository.findById.mockResolvedValue(league);
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    driverRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId } as GetLeagueMembershipsInput);

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();

    expect(presented.league).toEqual(league);
    expect(presented.memberships).toHaveLength(1);
    expect(presented.memberships[0]?.membership).toEqual(memberships[0]);
    expect(presented.memberships[0]?.driver).toBeNull();
  });

  it('should return error when league not found', async () => {
    const leagueId = 'non-existent-league';

    leagueRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId } as GetLeagueMembershipsInput);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueMembershipsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('LEAGUE_NOT_FOUND');
    expect(err.details?.message).toBe('League not found');
  });

  it('should return repository error on unexpected failure', async () => {
    const leagueId = 'league-1';

    leagueRepository.findById.mockImplementation(() => {
      throw new Error('Database connection failed');
    });

    const result = await useCase.execute({ leagueId } as GetLeagueMembershipsInput);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueMembershipsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details?.message).toBe('Database connection failed');
  });
});
