import { effect, inject, Injectable, resource, signal } from '@angular/core';
import { CrmTabMetadataService, PayerService } from '../services';
import { TabService } from '@isa/core/tabs';
import { CrmPayer } from '../schemas';

@Injectable()
export class CustomerPayerAddressResource {
  #payerService = inject(PayerService);

  #params = signal<{
    payerId: number | undefined;
  }>({
    payerId: undefined,
  });

  params(params: { payerId?: number }) {
    this.#params.update((p) => ({ ...p, ...params }));
  }

  readonly resource = resource({
    params: () => this.#params(),
    loader: async ({ params, abortSignal }): Promise<CrmPayer | undefined> => {
      if (!params.payerId) {
        return undefined;
      }

      const res = await this.#payerService.fetchPayer(
        {
          payerId: params.payerId,
        },
        abortSignal,
      );

      return res.result as CrmPayer;
    },
  });
}

@Injectable({ providedIn: 'root' })
export class SelectedCustomerPayerAddressResource extends CustomerPayerAddressResource {
  #tabId = inject(TabService).activatedTabId;
  #customerMetadata = inject(CrmTabMetadataService);

  constructor() {
    super();
    effect(() => {
      const tabId = this.#tabId();
      const payerId = tabId
        ? this.#customerMetadata.selectedPayerId(tabId)
        : undefined;
      this.params({ payerId });
    });
  }
}
