import {defineStore} from "pinia";
import {ingest, saveTelegramCustomer, heartbeat} from "@/utils/ftch.js";
import {toRaw} from "vue";
import {deserializeStartParams} from "@/helpers.js";

export const usePulseStore = defineStore('pulse', {
    state: () => ({
        tracking_id: null,
        campaign_id: null,
        customer_created_at: null,
    }),

    actions: {
        initFromStartParams() {
            const webapp = window.Telegram.WebApp;
            const startParam = webapp.initDataUnsafe.start_param;
            const deserialized = deserializeStartParams(startParam);
            this.tracking_id = deserialized?.tracking_id;
            this.campaign_id = deserialized?.campaign_id;
            console.debug('[Pulse] Init with start parameters: ', deserialized);
        },

        ingest(event, eventData = {}) {
            const idempotencyKey = crypto.randomUUID();
            ingest({
                event: event,
                idempotency_key: idempotencyKey,
                payload: {
                    webapp: window.Telegram.WebApp,
                    eventData: eventData,
                },
            })
                .then(() => console.debug('[Pulse] Event Ingested', event, eventData, idempotencyKey))
                .catch(err => console.error('Ingest failed:', err));
        },

        catchTelegramCustomerFromInitData() {
            const userData = window.Telegram?.WebApp?.initDataUnsafe?.user;
            if (userData) {
                console.debug('[Pulse] Saving Telegram customer data');
                saveTelegramCustomer(userData)
                    .then((response) => {
                        this.tracking_id = response?.data?.tracking_id || this.tracking_id || null;
                        this.customer_created_at = response?.data?.created_at || null;
                        console.debug(
                            '[Pulse] Telegram customer data saved successfully. Tracking ID: ',
                            toRaw(this.tracking_id)
                        );
                    })
                    .catch(() => console.warn('[Pulse] Failed to save Telegram customer data:', error));
            }
        },

        heartbeat() {
            heartbeat()
                .then(() => console.debug('[Pulse] Heartbeat sent'))
                .catch(err => console.warn('[Pulse] Heartbeat failed:', err));
        }
    },
});
