import type { Logger } from '@core/shared/domain/Logger';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { Team } from '../../domain/entities/Team';
import { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import { TeamRepository } from '../../domain/repositories/TeamRepository';
import {
    JoinTeamUseCase,
    type JoinTeamErrorCode,
    type JoinTeamInput
} from './JoinTeamUseCase';

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

  beforeEach(() => {
    teamRepository = {
      findById: vi.fn(),
    };
    membershipRepository = {
      getActiveMembershipForDriver: vi.fn(),
      getMembership: vi.fn(),
      saveMembership: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
      info: vi.fn(),
    };

    useCase = new JoinTeamUseCase(
      teamRepository as unknown as TeamRepository,
      membershipRepository as unknown as TeamMembershipRepository,
      logger,
    );
  });

  it('should successfully join a team', async () => {
    const input: JoinTeamInput = { teamId: 'team-1', driverId: 'driver-1' };
    const team = Team.create({
      id: 'team-1',
      name: 'Test Team',
      tag: 'TT',
      description: 'Test Description',
      ownerId: 'owner-1',
      leagues: [],
    });
    const membership = {
      teamId: 'team-1',
      driverId: 'driver-1',
      role: 'driver' as const,
      status: 'active' as const,
      joinedAt: new Date(),
    };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(null);
    membershipRepository.getMembership.mockResolvedValue(null);
    teamRepository.findById.mockResolvedValue(team);
    membershipRepository.saveMembership.mockResolvedValue(membership);

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const successResult = result.unwrap();
    expect(successResult.team).toBe(team);
    expect(successResult.membership).toBe(membership);
  });

  it('should return ALREADY_IN_TEAM error when driver already has active membership', async () => {
    const input: JoinTeamInput = { teamId: 'team-1', driverId: 'driver-1' };
    const existingMembership = {
      teamId: 'team-2',
      driverId: 'driver-1',
      role: 'driver' as const,
      status: 'active' as const,
      joinedAt: new Date(),
    };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(existingMembership);

    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');
  });

  it('should return ALREADY_MEMBER error when membership already exists', async () => {
    const input: JoinTeamInput = { teamId: 'team-1', driverId: 'driver-1' };
    const existingMembership = {
      teamId: 'team-1',
      driverId: 'driver-1',
      role: 'driver' as const,
      status: 'pending' as const,
      joinedAt: new Date(),
    };

    membershipRepository.getActiveMembershipForDriver.mockResolvedValue(null);
    membershipRepository.getMembership.mockResolvedValue(existingMembership);

    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');
  });

  it('should return TEAM_NOT_FOUND error when team does not exist', 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');
  });

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

    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 failure');
  });
});