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

@Injectable()
export class CustomerResource {
  #customerService = inject(CrmSearchService);

  protected _params = signal<{
    customerId: number | undefined;
    eagerLoading: number;
  }>({
    customerId: undefined,
    eagerLoading: 3,
  });

  params(params: { customerId?: number; eagerLoading?: number }) {
    this._params.update((p) => ({ ...p, ...params }));
  }

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

      const res = await this.#customerService.fetchCustomer(
        {
          customerId: params.customerId,
          eagerLoading: params.eagerLoading,
        },
        abortSignal,
      );

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

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

  constructor() {
    super();
    effect(() => {
      const tabId = this.#tabId();
      let customerId = undefined;

      if (tabId) {
        customerId = this.#customerMetadata.selectedCustomerId(tabId);
      }

      untracked(() => {
        if (this._params().customerId !== customerId) {
          this.params({ customerId });
        }
      });
    });
  }

  setEagerLoading(eagerLoading: number) {
    this.params({ eagerLoading });
  }
}
