import { defineStore } from 'pinia';
import { ref } from 'vue';

const getPixExpiresAt = (payment) => payment?.pix?.expires_at ?? payment?.expires_at ?? null;

const isFutureDate = (date) => {
  if (!date) return false;
  const time = new Date(date).getTime();
  return Number.isFinite(time) && time > Date.now();
};

export const usePaymentStore = defineStore('payment', () => {
  const pixPaymentsByServicePackageId = ref({});

  const getValidPixPaymentForServicePackage = (servicePackageId) => {
    const payment = pixPaymentsByServicePackageId.value[servicePackageId] ?? null;
    if (!payment) return null;

    if (!isFutureDate(getPixExpiresAt(payment))) {
      clearPixPaymentForServicePackage(servicePackageId);
      return null;
    }

    return payment;
  };

  const setPixPaymentForServicePackage = (servicePackageId, payment) => {
    if (!servicePackageId || !payment) return;
    pixPaymentsByServicePackageId.value = {
      ...pixPaymentsByServicePackageId.value,
      [servicePackageId]: payment,
    };
  };

  const clearPixPaymentForServicePackage = (servicePackageId) => {
    if (!servicePackageId || !pixPaymentsByServicePackageId.value[servicePackageId]) return;

    const payments = { ...pixPaymentsByServicePackageId.value };
    delete payments[servicePackageId];
    pixPaymentsByServicePackageId.value = payments;
  };

  return {
    pixPaymentsByServicePackageId,
    getValidPixPaymentForServicePackage,
    setPixPaymentForServicePackage,
    clearPixPaymentForServicePackage,
  };
});
