import { inject, Injectable } from '@angular/core';
import { CrmSearchService } from '../services/crm-search.service';
import { CheckBonInput, AddBonInput } from '../schemas';
import { LoyaltyBonResponse } from '@generated/swagger/crm-api';
import { ResponseArgs } from '@isa/common/data-access';

/**
 * Facade for customer Bon redemption operations.
 *
 * Provides a simplified API for validating and redeeming customer receipts (Bons)
 * for loyalty points.
 */
@Injectable({
  providedIn: 'root',
})
export class CustomerBonRedemptionFacade {
  #crmSearchService = inject(CrmSearchService);

  /**
   * Check/validate a Bon number
   *
   * @param params - Bon validation parameters
   * @param abortSignal - Optional abort signal for cancellation
   * @returns Response with Bon details (date, total)
   */
  async checkBon(
    params: CheckBonInput,
    abortSignal?: AbortSignal,
  ): Promise<ResponseArgs<LoyaltyBonResponse>> {
    // Fetch store ID if not provided
    if (!params.storeId) {
      const store =
        await this.#crmSearchService.fetchCurrentBookingPartnerStore();
      params = { ...params, storeId: store?.key };
    }

    return this.#crmSearchService.checkBon(params, abortSignal);
  }

  /**
   * Redeem/add a Bon for customer points
   *
   * @param params - Bon redemption parameters
   * @returns True if redemption successful, false otherwise
   */
  async addBon(params: AddBonInput): Promise<boolean> {
    // Fetch store ID if not provided
    if (!params.storeId) {
      const store =
        await this.#crmSearchService.fetchCurrentBookingPartnerStore();
      params = { ...params, storeId: store?.key };
    }

    return this.#crmSearchService.addBon(params);
  }
}
