import type { Logger } from '@core/shared/domain/Logger';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import { PenaltyRepository } from '../../domain/repositories/PenaltyRepository';
import { RaceRepository } from '../../domain/repositories/RaceRepository';
import { QuickPenaltyUseCase, type QuickPenaltyErrorCode, type QuickPenaltyInput } from './QuickPenaltyUseCase';

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

  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(),
    };
    useCase = new QuickPenaltyUseCase(penaltyRepository as unknown as PenaltyRepository,
      raceRepository as unknown as RaceRepository,
      leagueMembershipRepository as unknown as LeagueMembershipRepository,
      logger as unknown as Logger);
  });

  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);
    const penaltyResult = result.unwrap();
    expect(penaltyResult.raceId).toBe('race-1');
    expect(penaltyResult.driverId).toBe('driver-1');
    expect(penaltyResult.penaltyId).toBeDefined();
    expect(penaltyResult.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' },
    });
  });

  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' },
    });
  });

  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);
    const penaltyResult = result.unwrap();
    expect(penaltyResult.raceId).toBe('race-1');
    expect(penaltyResult.driverId).toBe('driver-1');
  });
});
