import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Team } from '../../domain/entities/Team';
import type { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import type { TeamRepository } from '../../domain/repositories/TeamRepository';
import type { TeamMembership } from '../../domain/types/TeamMembership';

export interface GetTeamDetailsInput {
  teamId: string;
  driverId: string;
}

export type GetTeamDetailsErrorCode = 'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface GetTeamDetailsResult {
  team: Team;
  membership: TeamMembership | null;
  canManage: boolean;
}

export class GetTeamDetailsUseCase {
  constructor(
    private readonly teamRepository: TeamRepository,
    private readonly membershipRepository: TeamMembershipRepository,
  ) {}

  async execute(
    input: GetTeamDetailsInput,
  ): Promise<Result<GetTeamDetailsResult, ApplicationErrorCode<GetTeamDetailsErrorCode, { message: string }>>> {
    try {
      const team = await this.teamRepository.findById(input.teamId);

      if (!team) {
        return Result.err({
          code: 'TEAM_NOT_FOUND',
          details: { message: 'Team not found' },
        });
      }

      const membership = input.driverId ? await this.membershipRepository.getMembership(input.teamId, input.driverId) : null;

      const canManage = membership ? (membership.role === 'owner' || membership.role === 'manager') : false;

      return Result.ok({
        team,
        membership: membership || null,
        canManage,
      });
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Failed to get team details';

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}