import { Injectable, inject, resource, signal, computed } from '@angular/core';
import { logger } from '@isa/core/logging';
import { CustomerBonRedemptionFacade } from '../facades/customer-bon-redemption.facade';
import { LoyaltyBonResponse } from '@generated/swagger/crm-api';

/**
 * Resource for checking/validating Bon numbers.
 *
 * Provides reactive loading of Bon details for validation.
 * Parameters can be updated via `params()` method to trigger validation.
 *
 * **Note:** Provide at component level, not root.
 */
@Injectable()
export class CustomerBonCheckResource {
  readonly #bonFacade = inject(CustomerBonRedemptionFacade);
  readonly #logger = logger(() => ({ context: 'CustomerBonCheckResource' }));

  readonly #cardCode = signal<string | undefined>(undefined);
  readonly #bonNr = signal<string | undefined>(undefined);

  /**
   * Resource that validates Bon based on current parameters.
   */
  readonly resource = resource({
    params: computed(() => ({
      cardCode: this.#cardCode(),
      bonNr: this.#bonNr(),
    })),
    loader: async ({
      params,
      abortSignal,
    }): Promise<LoyaltyBonResponse | undefined> => {
      const { cardCode, bonNr } = params;

      if (!cardCode || !bonNr) {
        return undefined;
      }

      this.#logger.debug('Checking Bon', () => ({ cardCode, bonNr }));

      const response = await this.#bonFacade.checkBon(
        { cardCode, bonNr },
        abortSignal,
      );

      this.#logger.debug('Bon checked', () => ({
        bonNr,
        found: !!response?.result,
      }));

      return response?.result;
    },
    defaultValue: undefined,
  });

  /**
   * Update parameters to trigger Bon validation.
   */
  params(params: { cardCode: string; bonNr: string }): void {
    this.#cardCode.set(params.cardCode);
    this.#bonNr.set(params.bonNr);
  }

  /**
   * Reset the resource state.
   */
  reset(): void {
    this.#cardCode.set(undefined);
    this.#bonNr.set(undefined);
  }
}
