import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { QuickPenaltyUseCase, type QuickPenaltyInput, type QuickPenaltyResult, type QuickPenaltyErrorCode } from './QuickPenaltyUseCase';
import type { IPenaltyRepository } from '../../domain/repositories/IPenaltyRepository';
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';


describe('QuickPenaltyUseCase', () => {
  let useCase: QuickPenaltyUseCase;
  let penaltyRepository: {
    create: Mock;
  };
  let raceRepository: {
    findById: Mock;
  };
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };
  let output: (UseCaseOutputPort<QuickPenaltyResult> & { present: Mock });

  beforeEach(() => {
    penaltyRepository = {
      create: vi.fn(),
    };
    raceRepository = {
      findById: vi.fn(),
    };
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<QuickPenaltyResult> & { present: Mock };

    useCase = new QuickPenaltyUseCase(
      penaltyRepository as unknown as IPenaltyRepository,
      raceRepository as unknown as IRaceRepository,
      leagueMembershipRepository as unknown as ILeagueMembershipRepository,
      logger as unknown as Logger,
      output,
    );
  });
  it('should apply penalty successfully', async () => {
    const input: QuickPenaltyInput = {
      raceId: 'race-1',
      driverId: 'driver-1',
      adminId: 'admin-1',
      infractionType: 'track_limits',
      severity: 'minor',
      notes: 'Test penalty',
    };

    raceRepository.findById.mockResolvedValue({ id: 'race-1', leagueId: 'league-1' });
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue([
      { driverId: { toString: () => 'admin-1' }, role: { toString: () => 'admin' }, status: { toString: () => 'active' } },
    ]);
    penaltyRepository.create.mockResolvedValue(undefined);

    const result = await useCase.execute(input);

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

    const presented = output.present.mock.calls[0]![0] as QuickPenaltyResult;
    expect(presented.raceId).toBe('race-1');
    expect(presented.driverId).toBe('driver-1');
    expect(presented.penaltyId).toBeDefined();
    expect(presented.type).toBeDefined();
  });

  it('should return error when race not found', async () => {
    const input: QuickPenaltyInput = {
      raceId: 'race-1',
      driverId: 'driver-1',
      adminId: 'admin-1',
      infractionType: 'track_limits',
      severity: 'minor',
    };

    raceRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<QuickPenaltyErrorCode, { message: string }>;
    expect(error).toEqual({
      code: 'RACE_NOT_FOUND',
      details: { message: 'Race not found' },
    });
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error when admin unauthorized', async () => {
    const input: QuickPenaltyInput = {
      raceId: 'race-1',
      driverId: 'driver-1',
      adminId: 'admin-1',
      infractionType: 'track_limits',
      severity: 'minor',
    };

    raceRepository.findById.mockResolvedValue({ id: 'race-1', leagueId: 'league-1' });
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue([
      { driverId: { toString: () => 'admin-1' }, role: { toString: () => 'member' }, status: { toString: () => 'active' } },
    ]);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<QuickPenaltyErrorCode, { message: string }>;
    expect(error).toEqual({
      code: 'UNAUTHORIZED',
      details: { message: 'Only league owners and admins can issue penalties' },
    });
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should handle other infraction type', async () => {
    const input: QuickPenaltyInput = {
      raceId: 'race-1',
      driverId: 'driver-1',
      adminId: 'admin-1',
      infractionType: 'other',
      severity: 'major',
    };

    raceRepository.findById.mockResolvedValue({ id: 'race-1', leagueId: 'league-1' });
    leagueMembershipRepository.getLeagueMembers.mockResolvedValue([
      { driverId: { toString: () => 'admin-1' }, role: { toString: () => 'admin' }, status: { toString: () => 'active' } },
    ]);
    penaltyRepository.create.mockResolvedValue(undefined);

    const result = await useCase.execute(input);

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