import { defineStore } from "pinia";
import type { Producto } from "~/types/Producto";
import type { DataCupon } from "~/types/promocion";

export const usePedidoStore = defineStore("pedido", {
  state: () => ({
    cart: [] as Producto[],
    cupon: {} as any
  }),

  getters: {
    totalCarrito: (state) =>
      state.cart.reduce((total, item) => total + item.subtotal, 0),
  },

  actions: {

    // :::::::::::::: Carrito ::::::::::::::
    addToCart(producto: Producto) {
      const existing = this.cart.find((item) => item.id === producto.id);
      if (!existing) {
        const subtotal = producto.cantidad * parseFloat(producto.precio);
        producto.subtotal = subtotal;
        this.cart.push(producto);
      } else {
        const index = this.cart.findIndex((item) => item.id === producto.id);
        this.cart[index]!.valvula_id = producto.valvula_id;
      }
    },
    decrease(producto: Producto) {
      const index = this.cart.findIndex((item) => item.id === producto.id);
      if (index === -1) return;
      const item = this.cart[index]!;
      if (item.cantidad !== 0) {
        item.cantidad--;
        item.subtotal = item.cantidad * parseFloat(item.precio);

        if (item.cantidad === 0) {
          this.removeFromCart(item.id);
        }
      }
    },
    increase(producto: Producto) {
      const index = this.cart.findIndex((item) => item.id === producto.id);
      if (index === -1) return;
      const item = this.cart[index]!;
      item.cantidad++;
      item.subtotal = item.cantidad * parseFloat(item.precio);
    },
    removeFromCart(productId: number) {
      const index = this.cart.findIndex((item) => item.id === productId);
      this.cart[index]!.cantidad = 0;
      this.cart = this.cart.filter((item) => item.id !== productId);
    },
    // :::::::::::::: Cupon ::::::::::::::
    setCupon(cupon: any) {
      this.cupon = {...cupon}
    }
  },
});
