import { Injectable, inject } from '@angular/core';
import { TabService, getMetadataHelper } from '@isa/core/tabs';
import {
  SELECTED_CUSTOMER_ID,
  SELECTED_PAYER_ADDRESS_ID,
  SELECTED_SHIPPING_ADDRESS_ID,
} from '../constants';
import z from 'zod';

@Injectable({ providedIn: 'root' })
export class CrmTabMetadataService {
  #tabService = inject(TabService);

  selectedCustomerId(tabId: number): number | undefined {
    return getMetadataHelper(
      tabId,
      SELECTED_CUSTOMER_ID,
      z.number().optional(),
      this.#tabService.entityMap(),
    );
  }

  selectedShippingAddressId(tabId: number): number | undefined {
    return getMetadataHelper(
      tabId,
      SELECTED_SHIPPING_ADDRESS_ID,
      z.number().optional(),
      this.#tabService.entityMap(),
    );
  }

  selectedPayerId(tabId: number): number | undefined {
    return getMetadataHelper(
      tabId,
      SELECTED_PAYER_ADDRESS_ID,
      z.number().optional(),
      this.#tabService.entityMap(),
    );
  }

  setSelectedCustomerId(tabId: number, customerId: number | undefined) {
    this.#tabService.patchTabMetadata(tabId, {
      [SELECTED_CUSTOMER_ID]: customerId,
    });
  }

  setSelectedShippingAddressId(
    tabId: number,
    shippingAddressId: number | undefined,
  ) {
    this.#tabService.patchTabMetadata(tabId, {
      [SELECTED_SHIPPING_ADDRESS_ID]: shippingAddressId,
    });
  }

  setSelectedPayerId(tabId: number, payerAddressId: number | undefined) {
    this.#tabService.patchTabMetadata(tabId, {
      [SELECTED_PAYER_ADDRESS_ID]: payerAddressId,
    });
  }
}
