import { inject, Injectable } from '@angular/core';
import { PayerService as GeneratedPayerService } from '@generated/swagger/crm-api';
import {
  catchResponseArgsErrorPipe,
  ResponseArgs,
  takeUntilAborted,
} from '@isa/common/data-access';
import { firstValueFrom } from 'rxjs';
import { logger } from '@isa/core/logging';
import { FetchPayerInput, FetchPayerSchema, CrmPayer } from '../schemas';

@Injectable({ providedIn: 'root' })
export class PayerService {
  #payerService = inject(GeneratedPayerService);
  #logger = logger(() => ({
    service: 'PayerService',
  }));

  async fetchPayer(
    params: FetchPayerInput,
    abortSignal?: AbortSignal,
  ): Promise<ResponseArgs<CrmPayer>> {
    this.#logger.info('Fetching payer from API');
    const { payerId } = FetchPayerSchema.parse(params);

    let req$ = this.#payerService
      .PayerGetPayer(payerId)
      .pipe(catchResponseArgsErrorPipe());

    if (abortSignal) {
      req$ = req$.pipe(takeUntilAborted(abortSignal));
    }

    try {
      const res = await firstValueFrom(req$);
      this.#logger.debug('Successfully fetched payer');
      return res as ResponseArgs<CrmPayer>;
    } catch (error) {
      this.#logger.error('Error fetching payer', error);
      return undefined as unknown as ResponseArgs<CrmPayer>;
    }
  }
}
