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 type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { StandingRepository } from '../../domain/repositories/StandingRepository';
import {
    GetLeagueOwnerSummaryUseCase,
    type GetLeagueOwnerSummaryErrorCode,
    type GetLeagueOwnerSummaryInput,
} from './GetLeagueOwnerSummaryUseCase';

describe('GetLeagueOwnerSummaryUseCase', () => {
  let useCase: GetLeagueOwnerSummaryUseCase;
  let leagueRepository: {
    findById: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let standingRepository: {
    findByDriverIdAndLeagueId: Mock;
    findByLeagueId: Mock;
  };

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

  it('should return owner summary when league and owner exist', async () => {
    const leagueId = 'league-1';
    const ownerId = 'owner-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'Desc',
      ownerId,
      settings: {},
    });
    const driver = Driver.create({
      id: ownerId,
      iracingId: '123',
      name: 'Owner Name',
      country: 'US',
    });

    leagueRepository.findById.mockResolvedValue(league);
    driverRepository.findById.mockResolvedValue(driver);
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue([]);
    standingRepository.findByDriverIdAndLeagueId.mockResolvedValue(null);

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

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();
    expect(presented.league).toBe(league);
    expect(presented.owner).toBe(driver);
    expect(presented.rating).toBeNull();
    expect(presented.rank).toBeNull();
  });

  it('should return error when league does not exist', async () => {
    const leagueId = 'league-1';

    leagueRepository.findById.mockResolvedValue(null);

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

    expect(result.isErr()).toBe(true);
    const errorResult = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueOwnerSummaryErrorCode,
      { message: string }
    >;
    expect(errorResult.code).toBe('LEAGUE_NOT_FOUND');
    expect(errorResult.details.message).toBe('League not found');
  });

  it('should return error when owner does not exist', async () => {
    const leagueId = 'league-1';
    const ownerId = 'owner-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'Desc',
      ownerId,
      settings: {},
    });

    leagueRepository.findById.mockResolvedValue(league);
    driverRepository.findById.mockResolvedValue(null);

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

    expect(result.isErr()).toBe(true);
    const errorResult = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueOwnerSummaryErrorCode,
      { message: string }
    >;
    expect(errorResult.code).toBe('OWNER_NOT_FOUND');
    expect(errorResult.details.message).toBe('League owner not found');
  });

  it('should return repository error when repository throws', async () => {
    const leagueId = 'league-1';

    leagueRepository.findById.mockRejectedValue(new Error('DB failure'));

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

    expect(result.isErr()).toBe(true);
    const errorResult = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueOwnerSummaryErrorCode,
      { message: string }
    >;

    expect(errorResult.code).toBe('REPOSITORY_ERROR');
    expect(errorResult.details.message).toBe('DB failure');
  });
});
