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

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;
  };
  let output: UseCaseOutputPort<JoinTeamResult> & { present: 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(),
    };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<JoinTeamResult> & { present: Mock };

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

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

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

    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 JoinTeamResult;
    expect(presented.team.id).toBe('team-1');
    expect(presented.membership.teamId).toBe('team-1');
    expect(presented.membership.driverId).toBe('driver-1');
    expect(presented.membership.role).toBe('driver');
    expect(presented.membership.status).toBe('active');
  });

  it('should return error when driver already in a team', async () => {
    const input: JoinTeamInput = { 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(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      JoinTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('ALREADY_IN_TEAM');
    expect(err.details.message).toBe('Driver already belongs to a team');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error when already a member', async () => {
    const input: JoinTeamInput = { 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(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      JoinTeamErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('ALREADY_MEMBER');
    expect(err.details.message).toBe(
      'Already a member or have a pending request',
    );
    expect(output.present).not.toHaveBeenCalled();
  });

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

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

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      JoinTeamErrorCode,
      { 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 on repository failure', async () => {
    const input: JoinTeamInput = { teamId: 'team-1', driverId: 'driver-1' };
    const error = new Error('Repository error');

    membershipRepository.getActiveMembershipForDriver.mockRejectedValue(error);

    const result = await useCase.execute(input);

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