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 CustomerShippingAddressesResource {
  #shippingAddressService = inject(ShippingAddressService);

  #params = signal<{
    customerId: number | undefined;
    take?: number | null;
    skip?: number | null;
  }>({
    customerId: undefined,
  });

  params(params: {
    customerId?: number;
    take?: number | null;
    skip?: number | null;
  }) {
    this.#params.update((p) => ({ ...p, ...params }));
  }

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

      const res =
        await this.#shippingAddressService.fetchCustomerShippingAddresses(
          {
            customerId: params.customerId,
            take: params.take,
            skip: params.skip,
          },
          abortSignal,
        );

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

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

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