import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { JoinTeamUseCase } from './JoinTeamUseCase';
import { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { Logger } from '@core/shared/application';

describe('JoinTeamUseCase', () => {
  let useCase: JoinTeamUseCase;
  let teamRepository: {
    findById: Mock;
  };
  let membershipRepository: {
    getActiveMembershipForDriver: Mock;
    getMembership: Mock;
    saveMembership: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };

  beforeEach(() => {
    teamRepository = {
      findById: vi.fn(),
    };
    membershipRepository = {
      getActiveMembershipForDriver: vi.fn(),
      getMembership: vi.fn(),
      saveMembership: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    useCase = new JoinTeamUseCase(
      teamRepository as unknown as ITeamRepository,
      membershipRepository as unknown as ITeamMembershipRepository,
      logger as unknown as Logger,
    );
  });

  it('should join team successfully', async () => {
    const command = { teamId: 'team-1', driverId: 'driver-1' };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(null);
    membershipRepository.getMembership.mockResolvedValue(null);
    teamRepository.findById.mockResolvedValue({ id: 'team-1' });
    membershipRepository.saveMembership.mockResolvedValue(undefined);

    const result = await useCase.execute(command);

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

  it('should return error when driver already in a team', async () => {
    const command = { teamId: 'team-1', driverId: 'driver-1' };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue({
      teamId: 'team-2',
      driverId: 'driver-1',
      role: 'driver',
      status: 'active',
      joinedAt: new Date(),
    });

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'ALREADY_IN_TEAM',
      details: { message: 'Driver already belongs to a team' },
    });
  });

  it('should return error when already a member', async () => {
    const command = { teamId: 'team-1', driverId: 'driver-1' };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(null);
    membershipRepository.getMembership.mockResolvedValue({
      teamId: 'team-1',
      driverId: 'driver-1',
      role: 'driver',
      status: 'pending',
      joinedAt: new Date(),
    });

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'ALREADY_MEMBER',
      details: { message: 'Already a member or have a pending request' },
    });
  });

  it('should return error when team not found', async () => {
    const command = { teamId: 'team-1', driverId: 'driver-1' };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(null);
    membershipRepository.getMembership.mockResolvedValue(null);
    teamRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'TEAM_NOT_FOUND',
      details: { message: 'Team team-1 not found' },
    });
  });

  it('should return error on repository failure', async () => {
    const command = { teamId: 'team-1', driverId: 'driver-1' };
    const error = new Error('Repository error');

    membershipRepository.getActiveMembershipForDriver.mockRejectedValue(error);

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'REPOSITORY_ERROR',
      details: { message: 'Repository error' },
    });
  });
});