import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
  SubmitProtestDefenseUseCase,
  type SubmitProtestDefenseInput,
  type SubmitProtestDefenseResult,
  type SubmitProtestDefenseErrorCode,
} from './SubmitProtestDefenseUseCase';
import type { IProtestRepository } from '../../domain/repositories/IProtestRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Result } from '@core/shared/application/Result';

interface MockProtest {
  id: string;
  accusedDriverId: string;
  canSubmitDefense: ReturnType<typeof vi.fn>;
  submitDefense: ReturnType<typeof vi.fn>;
}

describe('SubmitProtestDefenseUseCase', () => {
  let leagueRepository: ILeagueRepository & { findById: ReturnType<typeof vi.fn> };
  let protestRepository: IProtestRepository & { findById: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> };
  let logger: Logger & { error: ReturnType<typeof vi.fn> };
  let output: UseCaseOutputPort<SubmitProtestDefenseResult> & { present: ReturnType<typeof vi.fn> };
  let useCase: SubmitProtestDefenseUseCase;

  const createInput = (overrides: Partial<SubmitProtestDefenseInput> = {}): SubmitProtestDefenseInput => ({
    leagueId: 'league-1',
    protestId: 'protest-1',
    driverId: 'driver-1',
    defenseText: 'My defense',
    videoUrl: 'http://video.com',
    ...overrides,
  });

  const unwrapError = (
    result: Result<void, ApplicationErrorCode<SubmitProtestDefenseErrorCode, { message: string }>>,
  ): ApplicationErrorCode<SubmitProtestDefenseErrorCode, { message: string }> => {
    expect(result.isErr()).toBe(true);
    return result.unwrapErr();
  };

  beforeEach(() => {
    leagueRepository = {
      findById: vi.fn(),
      findAll: vi.fn(),
      findByOwnerId: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      exists: vi.fn(),
      searchByName: vi.fn(),
    } as unknown as ILeagueRepository & { findById: ReturnType<typeof vi.fn> };

    protestRepository = {
      findById: vi.fn(),
      findByRaceId: vi.fn(),
      findByProtestingDriverId: vi.fn(),
      findByAccusedDriverId: vi.fn(),
      findPending: vi.fn(),
      findUnderReviewBy: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      exists: vi.fn(),
    } as unknown as IProtestRepository & {
      findById: ReturnType<typeof vi.fn>;
      update: ReturnType<typeof vi.fn>;
    };

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger & { error: ReturnType<typeof vi.fn> };

    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<SubmitProtestDefenseResult> & { present: ReturnType<typeof vi.fn> };

    useCase = new SubmitProtestDefenseUseCase(
      leagueRepository as unknown as ILeagueRepository,
      protestRepository as unknown as IProtestRepository,
      logger as unknown as Logger,
      output,
    );
  });

  it('submits defense successfully', async () => {
    const mockProtest: MockProtest = {
      id: 'protest-1',
      accusedDriverId: 'driver-1',
      canSubmitDefense: vi.fn().mockReturnValue(true),
      submitDefense: vi.fn().mockReturnValue({ id: 'protest-1' }),
    } as unknown as MockProtest;

    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    protestRepository.findById.mockResolvedValue(mockProtest);
    protestRepository.update.mockResolvedValue(undefined);

    const input = createInput();

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();
    expect(leagueRepository.findById).toHaveBeenCalledWith('league-1');
    expect(protestRepository.findById).toHaveBeenCalledWith('protest-1');
    expect(mockProtest.canSubmitDefense).toHaveBeenCalled();
    expect(mockProtest.submitDefense).toHaveBeenCalledWith('My defense', 'http://video.com');
    expect(protestRepository.update).toHaveBeenCalled();
    expect(output.present).toHaveBeenCalledTimes(1);
    expect(output.present).toHaveBeenCalledWith({
      leagueId: 'league-1',
      protestId: 'protest-1',
      driverId: 'driver-1',
      status: 'defense_submitted',
    });
  });

  it('returns error when league not found', async () => {
    leagueRepository.findById.mockResolvedValue(null);

    const input = createInput();

    const result = await useCase.execute(input);

    const error = unwrapError(result);
    expect(error.code).toBe('LEAGUE_NOT_FOUND');
    expect(error.details?.message).toBe('League not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns error when protest not found', async () => {
    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    protestRepository.findById.mockResolvedValue(null);

    const input = createInput();

    const result = await useCase.execute(input);

    const error = unwrapError(result);
    expect(error.code).toBe('PROTEST_NOT_FOUND');
    expect(error.details?.message).toBe('Protest not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns error when driver is not allowed', async () => {
    const mockProtest = {
      id: 'protest-1',
      accusedDriverId: 'driver-2',
    } as unknown as MockProtest;

    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    protestRepository.findById.mockResolvedValue(mockProtest);

    const input = createInput({ driverId: 'driver-1' });

    const result = await useCase.execute(input);

    const error = unwrapError(result);
    expect(error.code).toBe('DRIVER_NOT_ALLOWED');
    expect(error.details?.message).toBe('Driver is not allowed to submit a defense for this protest');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns error when defense cannot be submitted due to invalid state', async () => {
    const mockProtest: MockProtest = {
      id: 'protest-1',
      accusedDriverId: 'driver-1',
      canSubmitDefense: vi.fn().mockReturnValue(false),
      submitDefense: vi.fn(),
    } as unknown as MockProtest;

    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    protestRepository.findById.mockResolvedValue(mockProtest);

    const input = createInput();

    const result = await useCase.execute(input);

    const error = unwrapError(result);
    expect(error.code).toBe('INVALID_PROTEST_STATE');
    expect(error.details?.message).toBe('Defense cannot be submitted for this protest');
    expect(output.present).not.toHaveBeenCalled();
    expect(mockProtest.submitDefense).not.toHaveBeenCalled();
  });

  it('returns repository error when update throws', async () => {
    const mockProtest: MockProtest = {
      id: 'protest-1',
      accusedDriverId: 'driver-1',
      canSubmitDefense: vi.fn().mockReturnValue(true),
      submitDefense: vi.fn().mockReturnValue({ id: 'protest-1' }),
    } as unknown as MockProtest;

    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    protestRepository.findById.mockResolvedValue(mockProtest);
    protestRepository.update.mockRejectedValue(new Error('DB failure'));

    const input = createInput();

    const result = await useCase.execute(input);

    const error = unwrapError(result);
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details?.message).toBe('DB failure');
    expect(output.present).not.toHaveBeenCalled();
    expect(logger.error).toHaveBeenCalled();
  });
});
