import { Injectable, inject } from '@angular/core';
import { TabService, getMetadataHelper } from '@isa/core/tabs';
import {
  CHECKOUT_REWARD_SELECTION_POPUP_OPENED_STATE_KEY,
  CHECKOUT_REWARD_SHOPPING_CART_ID_METADATA_KEY,
  CHECKOUT_SHOPPING_CART_ID_METADATA_KEY,
  SELECTED_BRANCH_METADATA_KEY,
} from '../constants';
import z from 'zod';
import { Branch, BranchSchema } from '../schemas/branch.schema';

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

  setSelectedBranch(tabId: number, branch: Branch | undefined) {
    this.#tabService.patchTabMetadata(tabId, {
      [SELECTED_BRANCH_METADATA_KEY]: branch,
    });
  }

  getSelectedBranch(tabId: number): Branch | undefined {
    return getMetadataHelper(
      tabId,
      SELECTED_BRANCH_METADATA_KEY,
      BranchSchema.optional(),
      this.#tabService.entityMap(),
    );
  }

  setShoppingCartId(tabId: number, shoppingCartId: number | undefined) {
    this.#tabService.patchTabMetadata(tabId, {
      [CHECKOUT_SHOPPING_CART_ID_METADATA_KEY]: shoppingCartId,
    });
  }

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

  setRewardShoppingCartId(tabId: number, shoppingCartId: number | undefined) {
    this.#tabService.patchTabMetadata(tabId, {
      [CHECKOUT_REWARD_SHOPPING_CART_ID_METADATA_KEY]: shoppingCartId,
    });
  }

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

  setRewardSelectionPopupOpenedState(
    tabId: number,
    opened: boolean | undefined,
  ) {
    this.#tabService.patchTabMetadata(tabId, {
      [CHECKOUT_REWARD_SELECTION_POPUP_OPENED_STATE_KEY]: opened,
    });
  }

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