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

@Injectable()
export class CustomerShippingAddressResource {
  #shippingAddressService = inject(ShippingAddressService);

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

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

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

      const res = await this.#shippingAddressService.fetchShippingAddress(
        {
          shippingAddressId: params.shippingAddressId,
        },
        abortSignal,
      );

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

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

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