import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetTeamJoinRequestsUseCase,
  type GetTeamJoinRequestsInput,
  type GetTeamJoinRequestsResult,
  type GetTeamJoinRequestsErrorCode,
} from './GetTeamJoinRequestsUseCase';
import { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import { Driver } from '../../domain/entities/Driver';
import { Team } from '../../domain/entities/Team';
import type { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetTeamJoinRequestsUseCase', () => {
  let useCase: GetTeamJoinRequestsUseCase;
  let membershipRepository: {
    getJoinRequests: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let teamRepository: {
    findById: Mock;
  };
  let output: UseCaseOutputPort<GetTeamJoinRequestsResult> & { present: Mock };

  beforeEach(() => {
    membershipRepository = {
      getJoinRequests: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    teamRepository = {
      findById: vi.fn(),
    };
    output = {
      present: vi.fn(),
    };

    useCase = new GetTeamJoinRequestsUseCase(
      membershipRepository as unknown as ITeamMembershipRepository,
      driverRepository as unknown as IDriverRepository,
      teamRepository as unknown as ITeamRepository,
      output,
    );
  });

  it('should return join requests with drivers when team exists', async () => {
    const teamId = 'team-1';
    const input: GetTeamJoinRequestsInput = { teamId };

    const joinRequests = [
      { id: 'req-1', teamId, driverId: 'driver-1', requestedAt: new Date(), message: 'msg' },
    ];

    const driver = Driver.create({
      id: 'driver-1',
      iracingId: '123',
      name: 'Driver 1',
      country: 'US',
    });

    const team = Team.create({
      id: teamId,
      name: 'Team 1',
      tag: 'T1',
      description: 'Description',
      ownerId: 'owner-1',
      leagues: [],
    });

    teamRepository.findById.mockResolvedValue(team);
    membershipRepository.getJoinRequests.mockResolvedValue(joinRequests);
    driverRepository.findById.mockResolvedValue(driver);

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();

    expect(output.present).toHaveBeenCalledTimes(1);
    const presentedRaw = output.present.mock.calls[0]?.[0];
    expect(presentedRaw).toBeDefined();
    const presented = presentedRaw as GetTeamJoinRequestsResult;

    expect(presented.team).toBe(team);
    expect(presented.joinRequests).toHaveLength(1);
    expect(presented.joinRequests[0]!).toMatchObject({
      id: 'req-1',
      teamId,
      driverId: 'driver-1',
      message: 'msg',
    });
    expect(presented.joinRequests[0]!.driver).toBe(driver);
  });

  it('should return TEAM_NOT_FOUND error when team does not exist', async () => {
    const teamId = 'missing-team';
    const input: GetTeamJoinRequestsInput = { teamId };

    teamRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetTeamJoinRequestsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('TEAM_NOT_FOUND');
    expect(err.details.message).toBe('Team not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return REPOSITORY_ERROR when repository throws', async () => {
    const teamId = 'team-1';
    const input: GetTeamJoinRequestsInput = { teamId };
    const error = new Error('Repository failure');

    teamRepository.findById.mockRejectedValue(error);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetTeamJoinRequestsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('Repository failure');
    expect(output.present).not.toHaveBeenCalled();
  });
});
