import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  LeaveTeamUseCase,
  type LeaveTeamInput,
  type LeaveTeamResult,
  type LeaveTeamErrorCode,
} from './LeaveTeamUseCase';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('LeaveTeamUseCase', () => {
  let useCase: LeaveTeamUseCase;
  let teamRepository: { findById: Mock };
  let membershipRepository: {
    getMembership: Mock;
    removeMembership: Mock;
  };
  let logger: Logger;
  let output: UseCaseOutputPort<LeaveTeamResult> & { present: Mock };

  beforeEach(() => {
    teamRepository = {
      findById: vi.fn(),
    };
    membershipRepository = {
      getMembership: vi.fn(),
      removeMembership: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<LeaveTeamResult> & { present: Mock };

    useCase = new LeaveTeamUseCase(
      teamRepository as unknown as ITeamRepository,
      membershipRepository as unknown as ITeamMembershipRepository,
      logger,
      output,
    );
  });

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

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

    const result = await useCase.execute(input);

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

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]![0] as LeaveTeamResult;
    expect(presented.team.id).toBe('team-1');
    expect(presented.previousMembership).toEqual(membership);
  });

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

    teamRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      LeaveTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('TEAM_NOT_FOUND');
    expect(err.details.message).toBe('Team team-1 not found');
    expect(output.present).not.toHaveBeenCalled();
  });

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

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

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      LeaveTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('NOT_MEMBER');
    expect(err.details.message).toBe('Not a member of this team');
    expect(output.present).not.toHaveBeenCalled();
  });

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

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

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      LeaveTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('OWNER_CANNOT_LEAVE');
    expect(err.details.message).toBe(
      'Team owner cannot leave. Transfer ownership or disband team first.',
    );
    expect(output.present).not.toHaveBeenCalled();
  });

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

    teamRepository.findById.mockRejectedValue(error);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      LeaveTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('Repository error');
    expect(output.present).not.toHaveBeenCalled();
  });
});