import { effect, inject, Injectable, resource, signal } from '@angular/core';
import { CrmTabMetadataService } from '../services';
import { TabService } from '@isa/core/tabs';
import { CrmCustomerService } from '@domain/crm';
import { PayerDTO } from '@generated/swagger/crm-api';

@Injectable()
export class PayerResource {
  #customerService = inject(CrmCustomerService);

  #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<PayerDTO | undefined> => {
      if (!params.payerId) {
        return undefined;
      }

      const res = await this.#customerService
        .getPayer(params.payerId)
        .toPromise();

      return res?.result;
    },
  });
}

@Injectable({ providedIn: 'root' })
export class SelectedPayerResource extends PayerResource {
  #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 });
    });
  }
}
