/**
 * AvailabilityValidationService
 *
 * Domain service for validating container availability
 *
 * Business Rules:
 * - Check if rate quote is still valid (not expired)
 * - Verify requested quantity is available
 */

import {
  ValidateAvailabilityPort,
  AvailabilityInput,
  AvailabilityOutput,
} from '@domain/ports/in/validate-availability.port';
import { RateQuoteRepository } from '@domain/ports/out/rate-quote.repository';
import { InvalidRateQuoteException } from '../exceptions/invalid-rate-quote.exception';
import { RateQuoteExpiredException } from '../exceptions/rate-quote-expired.exception';

export class AvailabilityValidationService implements ValidateAvailabilityPort {
  constructor(private readonly rateQuoteRepository: RateQuoteRepository) {}

  async execute(input: AvailabilityInput): Promise<AvailabilityOutput> {
    // Find rate quote
    const rateQuote = await this.rateQuoteRepository.findById(input.rateQuoteId);

    if (!rateQuote) {
      throw new InvalidRateQuoteException(`Rate quote not found: ${input.rateQuoteId}`);
    }

    // Check if rate quote has expired
    if (rateQuote.isExpired()) {
      throw new RateQuoteExpiredException(rateQuote.id, rateQuote.validUntil);
    }

    // Check availability
    const availableQuantity = rateQuote.availability;
    const isAvailable = availableQuantity >= input.quantity;

    return {
      isAvailable,
      availableQuantity,
      requestedQuantity: input.quantity,
      rateQuoteId: rateQuote.id,
      validUntil: rateQuote.validUntil,
    };
  }
}
