import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { TeamDetailsViewModel } from '../presenters/ITeamDetailsPresenter';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

/**
 * Use Case for retrieving team details.
 */
export class GetTeamDetailsUseCase {
  constructor(
    private readonly teamRepository: ITeamRepository,
    private readonly membershipRepository: ITeamMembershipRepository,
  ) {}

  async execute(
    params: { teamId: string; driverId: string },
  ): Promise<Result<TeamDetailsViewModel, ApplicationErrorCode<'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR'>>> {
    try {
      const { teamId, driverId } = params;
      const team = await this.teamRepository.findById(teamId);
      if (!team) {
        return Result.err({ code: 'TEAM_NOT_FOUND', message: 'Team not found' });
      }

      const membership = await this.membershipRepository.getMembership(teamId, driverId);

      const viewModel: TeamDetailsViewModel = {
        team: {
          id: team.id,
          name: team.name,
          tag: team.tag,
          description: team.description,
          ownerId: team.ownerId,
          leagues: team.leagues,
          createdAt: team.createdAt.toISOString(),
        },
        membership: membership ? {
          role: membership.role as 'owner' | 'manager' | 'member',
          joinedAt: membership.joinedAt.toISOString(),
          isActive: membership.status === 'active',
        } : null,
        canManage: membership ? membership.role === 'owner' || membership.role === 'manager' : false,
      };

      return Result.ok(viewModel);
    } catch {
      return Result.err({ code: 'REPOSITORY_ERROR', message: 'Failed to fetch team details' });
    }
  }
}