import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import {
  GetLeagueMembershipsUseCase,
  type GetLeagueMembershipsInput,
  type GetLeagueMembershipsResult,
  type GetLeagueMembershipsErrorCode,
} from './GetLeagueMembershipsUseCase';
import { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { LeagueMembership } from '../../domain/entities/LeagueMembership';
import { Driver } from '../../domain/entities/Driver';
import { League } from '../../domain/entities/League';
import type { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetLeagueMembershipsUseCase', () => {
  let useCase: GetLeagueMembershipsUseCase;
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let leagueRepository: {
    findById: Mock;
  };
  let output: UseCaseOutputPort<GetLeagueMembershipsResult> & { present: Mock };

  beforeEach(() => {
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    leagueRepository = {
      findById: vi.fn(),
    };
    output = {
      present: vi.fn(),
    };
    useCase = new GetLeagueMembershipsUseCase(
      leagueMembershipRepository as unknown as ILeagueMembershipRepository,
      driverRepository as unknown as IDriverRepository,
      leagueRepository as unknown as ILeagueRepository,
      output,
    );
  });

  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);
    expect(result.unwrap()).toBeUndefined();

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]?.[0] as GetLeagueMembershipsResult;

    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);
    expect(result.unwrap()).toBeUndefined();

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]?.[0] as GetLeagueMembershipsResult;

    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');
    expect(output.present).not.toHaveBeenCalled();
  });

  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');
    expect(output.present).not.toHaveBeenCalled();
  });
});