import { loadStripe, type Stripe } from "@stripe/stripe-js";
import axios from "axios"
import { jwtDecode } from 'jwt-decode'
import type { SessionDetailsInterface } from "./interface/session_details.interface";

export const usePaymentsGateway = defineStore("payments-gateway", () => {

    const runtimeConfig = useRuntimeConfig();

    const stripe_instance = ref<Stripe>(null);

    const getStripe = async () => {
        return await loadStripe(runtimeConfig.public.stripe_public_key);
    }


    /**
     * Valida el customer
     * @returns 
     */
    const validCustomer = async () => {
        try {
            const access_token = useCookie('access_token').value || '';

            const response = await axios.get(`${runtimeConfig.public.api_url}/api/payments-gateway/customer`,
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );

            if(response.data) {
                return false;
            } else {
                return true;
            }
            
        } catch (error) {
            return false;
        }
    }

    /**
     * Obtiene la sesión de la pasarela de pagos
     * @returns 
     */
    const getStripeSession = async (): Promise<SessionDetailsInterface> => {
        try {
            const access_token = useCookie('access_token').value || '';

            const response = await axios.post(`${runtimeConfig.public.api_url}/api/payments-gateway/checkout_session`, 
                {}, 
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );
    
            if(response.data) {
                const decoded = jwtDecode(response.data.SID) as SessionDetailsInterface;
                console.log(decoded, ' decodeddd');
                return decoded;
            }
            
            return null;
        } catch (error) {
            console.error(error, ' error desde paymentsGateway');
            return null;
        }
    }

    return {
        getStripe,
        validCustomer,
        getStripeSession,

        stripe_instance,
    }
})