import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { ApproveTeamJoinRequestUseCase } from './ApproveTeamJoinRequestUseCase';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';

describe('ApproveTeamJoinRequestUseCase', () => {
  let useCase: ApproveTeamJoinRequestUseCase;
  let membershipRepository: {
    getJoinRequests: Mock;
    removeJoinRequest: Mock;
    saveMembership: Mock;
  };

  beforeEach(() => {
    membershipRepository = {
      getJoinRequests: vi.fn(),
      removeJoinRequest: vi.fn(),
      saveMembership: vi.fn(),
    };
    useCase = new ApproveTeamJoinRequestUseCase(membershipRepository as unknown as ITeamMembershipRepository);
  });

  it('should approve join request and save membership', async () => {
    const teamId = 'team-1';
    const requestId = 'req-1';
    const joinRequests = [{ id: requestId, teamId, driverId: 'driver-1', requestedAt: new Date(), message: 'msg' }];

    membershipRepository.getJoinRequests.mockResolvedValue(joinRequests);

    const result = await useCase.execute({ teamId, requestId });

    expect(result.isOk()).toBe(true);
    expect(membershipRepository.removeJoinRequest).toHaveBeenCalledWith(requestId);
    expect(membershipRepository.saveMembership).toHaveBeenCalledWith({
      teamId,
      driverId: 'driver-1',
      role: 'driver',
      status: 'active',
      joinedAt: expect.any(Date),
    });
  });

  it('should return error if request not found', async () => {
    membershipRepository.getJoinRequests.mockResolvedValue([]);

    const result = await useCase.execute({ teamId: 'team-1', requestId: 'req-1' });

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toBe('JOIN_REQUEST_NOT_FOUND');
  });
});