import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import {
  GetTeamDetailsUseCase,
  type GetTeamDetailsInput,
  type GetTeamDetailsResult,
  type GetTeamDetailsErrorCode,
} from './GetTeamDetailsUseCase';
import { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import { Team } from '../../domain/entities/Team';
import type { TeamMembership } from '../../domain/types/TeamMembership';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetTeamDetailsUseCase', () => {
  let useCase: GetTeamDetailsUseCase;
  let teamRepository: {
    findById: Mock;
  };
  let membershipRepository: {
    getMembership: Mock;
  };
  let output: UseCaseOutputPort<GetTeamDetailsResult> & { present: Mock };

  beforeEach(() => {
    teamRepository = {
      findById: vi.fn(),
    };
    membershipRepository = {
      getMembership: vi.fn(),
    };
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetTeamDetailsResult> & { present: Mock };
    useCase = new GetTeamDetailsUseCase(
      teamRepository as unknown as ITeamRepository,
      membershipRepository as unknown as ITeamMembershipRepository,
      output,
    );
  });

  it('should return team details with membership', async () => {
    const teamId = 'team-1';
    const driverId = 'driver-1';
    const team = Team.create({
      id: teamId,
      name: 'Test Team',
      tag: 'TT',
      description: 'Test',
      ownerId: 'owner-1',
      leagues: [],
    });
    const membership: TeamMembership = {
      teamId,
      driverId,
      role: 'driver',
      status: 'active',
      joinedAt: new Date(),
    };

    teamRepository.findById.mockResolvedValue(team);
    membershipRepository.getMembership.mockResolvedValue(membership);

    const input: GetTeamDetailsInput = { teamId, driverId };

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);
    const presentedRaw = output.present.mock.calls[0]?.[0];
    expect(presentedRaw).toBeDefined();
    const presented = presentedRaw as GetTeamDetailsResult;
    expect(presented.team).toBe(team);
    expect(presented.membership).toEqual(membership);
    expect(presented.canManage).toBe(false);
  });

  it('should return team details for owner', async () => {
    const teamId = 'team-1';
    const driverId = 'driver-1';
    const team = Team.create({
      id: teamId,
      name: 'Test Team',
      tag: 'TT',
      description: 'Test',
      ownerId: driverId,
      leagues: [],
    });
    const membership: TeamMembership = {
      teamId,
      driverId,
      role: 'owner',
      status: 'active',
      joinedAt: new Date(),
    };

    teamRepository.findById.mockResolvedValue(team);
    membershipRepository.getMembership.mockResolvedValue(membership);

    const input: GetTeamDetailsInput = { teamId, driverId };

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);
    const presentedRaw = output.present.mock.calls[0]?.[0];
    expect(presentedRaw).toBeDefined();
    const presented = presentedRaw as GetTeamDetailsResult;
    expect(presented.canManage).toBe(true);
  });

  it('should return error for non-existing team', async () => {
    const teamId = 'team-1';
    const driverId = 'driver-1';
    teamRepository.findById.mockResolvedValue(null);

    const input: GetTeamDetailsInput = { teamId, driverId };

    const result = await useCase.execute(input);

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

  it('should return error on repository failure', async () => {
    const teamId = 'team-1';
    const driverId = 'driver-1';
    teamRepository.findById.mockRejectedValue(new Error('DB error'));

    const input: GetTeamDetailsInput = { teamId, driverId };

    const result = await useCase.execute(input);

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