/**
 * Use Case: RejectSponsorshipRequestUseCase
 *
 * Allows an entity owner to reject a sponsorship request.
 */

import type { ISponsorshipRequestRepository } from '../../domain/repositories/ISponsorshipRequestRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export interface RejectSponsorshipRequestDTO {
  requestId: string;
  respondedBy: string; // driverId of the person rejecting
  reason?: string;
}

export interface RejectSponsorshipRequestResultDTO {
  requestId: string;
  status: 'rejected';
  rejectedAt: Date;
  reason?: string;
}

export class RejectSponsorshipRequestUseCase {
  constructor(
    private readonly sponsorshipRequestRepo: ISponsorshipRequestRepository,
  ) {}

  async execute(dto: RejectSponsorshipRequestDTO): Promise<Result<RejectSponsorshipRequestResultDTO, ApplicationErrorCode<'SPONSORSHIP_REQUEST_NOT_FOUND' | 'SPONSORSHIP_REQUEST_NOT_PENDING'>>> {
    // Find the request
    const request = await this.sponsorshipRequestRepo.findById(dto.requestId);
    if (!request) {
      return Result.err({ code: 'SPONSORSHIP_REQUEST_NOT_FOUND' });
    }

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

    // Reject the request
    const rejectedRequest = request.reject(dto.respondedBy, dto.reason);
    await this.sponsorshipRequestRepo.update(rejectedRequest);

    // TODO: In a real implementation, notify the sponsor

    return Result.ok({
      requestId: rejectedRequest.id,
      status: 'rejected',
      rejectedAt: rejectedRequest.respondedAt!,
      ...(rejectedRequest.rejectionReason !== undefined
        ? { reason: rejectedRequest.rejectionReason }
        : {}),
    });
  }
}