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

describe('LeaveTeamUseCase', () => {
  let useCase: LeaveTeamUseCase;
  let membershipRepository: {
    getMembership: Mock;
    removeMembership: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };

  beforeEach(() => {
    membershipRepository = {
      getMembership: vi.fn(),
      removeMembership: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    useCase = new LeaveTeamUseCase(
      membershipRepository as unknown as ITeamMembershipRepository,
      logger as unknown as Logger,
    );
  });

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

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

    const result = await useCase.execute(command);

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

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

    membershipRepository.getMembership.mockResolvedValue(null);

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'NOT_MEMBER',
      details: { message: 'Not a member of this team' },
    });
  });

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

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

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'OWNER_CANNOT_LEAVE',
      details: { message: 'Team owner cannot leave. Transfer ownership or disband team first.' },
    });
  });

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

    membershipRepository.getMembership.mockRejectedValue(error);

    const result = await useCase.execute(command);

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