import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type {
  TeamMembership,
  TeamJoinRequest,
} from '../../domain/types/TeamMembership';
import type { ApproveTeamJoinRequestCommandDTO } from '../dtos/ApproveTeamJoinRequestCommandDTO';
import type { AsyncUseCase } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export class ApproveTeamJoinRequestUseCase
  implements AsyncUseCase<ApproveTeamJoinRequestCommandDTO, void, string> {
  constructor(
    private readonly membershipRepository: ITeamMembershipRepository,
  ) {}

  async execute(command: ApproveTeamJoinRequestCommandDTO): Promise<Result<void, ApplicationErrorCode<string>>> {
    const { teamId, requestId } = command;

    const allRequests: TeamJoinRequest[] = await this.membershipRepository.getJoinRequests(teamId);
    const request = allRequests.find((r) => r.id === requestId);

    if (!request) {
      return Result.err({ code: 'JOIN_REQUEST_NOT_FOUND' });
    }

    const membership: TeamMembership = {
      teamId: request.teamId,
      driverId: request.driverId,
      role: 'driver',
      status: 'active',
      joinedAt: new Date(),
    };

    await this.membershipRepository.saveMembership(membership);
    await this.membershipRepository.removeJoinRequest(requestId);
    return Result.ok(undefined);
  }
}