import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import {
  GetLeagueOwnerSummaryUseCase,
  type GetLeagueOwnerSummaryInput,
  type GetLeagueOwnerSummaryResult,
  type GetLeagueOwnerSummaryErrorCode,
} from './GetLeagueOwnerSummaryUseCase';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Driver } from '../../domain/entities/Driver';
import { League } from '../../domain/entities/League';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort } from '@core/shared/application';

describe('GetLeagueOwnerSummaryUseCase', () => {
  let useCase: GetLeagueOwnerSummaryUseCase;
  let leagueRepository: {
    findById: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let output: UseCaseOutputPort<GetLeagueOwnerSummaryResult> & { present: Mock };

  beforeEach(() => {
    leagueRepository = {
      findById: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetLeagueOwnerSummaryResult> & { present: Mock };

    useCase = new GetLeagueOwnerSummaryUseCase(
      leagueRepository as unknown as ILeagueRepository,
      driverRepository as unknown as IDriverRepository,
      output,
    );
  });

  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);

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

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);

    const presented = output.present.mock.calls[0]?.[0] as GetLeagueOwnerSummaryResult;

    expect(presented?.league).toBe(league);
    expect(presented?.owner).toBe(driver);
    expect(presented?.rating).toBe(0);
    expect(presented?.rank).toBe(0);
  });

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

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

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