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 pixPaymentsByScheduleId = ref({});

  const getValidPixPayment = (scheduleId) => {
    const payment = pixPaymentsByScheduleId.value[scheduleId] ?? null;
    if (!payment) return null;

    if (!isFutureDate(getPixExpiresAt(payment))) {
      clearPixPayment(scheduleId);
      return null;
    }

    return payment;
  };

  const setPixPayment = (scheduleId, payment) => {
    if (!scheduleId || !payment) return;
    pixPaymentsByScheduleId.value = {
      ...pixPaymentsByScheduleId.value,
      [scheduleId]: payment,
    };
  };

  const clearPixPayment = (scheduleId) => {
    if (!scheduleId || !pixPaymentsByScheduleId.value[scheduleId]) return;

    const payments = { ...pixPaymentsByScheduleId.value };
    delete payments[scheduleId];
    pixPaymentsByScheduleId.value = payments;
  };

  return {
    pixPaymentsByScheduleId,
    getValidPixPayment,
    setPixPayment,
    clearPixPayment,
  };
});
