/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { createStore } from 'zustand/vanilla';
import { useStore } from 'zustand';
import { requestDatalayerAPI, } from '../../api/DatalayerApi.js';
import { asSurvey, } from '../../models/index.js';
import { coreStore } from './CoreState.js';
import { iamStore } from './IAMState.js';
export const surveysStore = createStore((set, get) => ({
    surveys: undefined,
    growthRunUrl: coreStore.getState().configuration?.growthRunUrl,
    setSurveys: (s) => {
        const surveys = new Map();
        s.forEach(survey => surveys.set(survey.name, survey));
        set((state) => ({ surveys }));
    },
    refreshSurveys: async () => {
        const { token } = iamStore.getState();
        const { growthRunUrl } = get();
        try {
            const resp = await requestDatalayerAPI({
                url: `${growthRunUrl}/api/growth/v1/surveys`,
                method: 'GET',
                token,
            });
            if (resp.success && resp.surveys) {
                const surveyArray = resp.surveys.map(survey => asSurvey(survey));
                const surveys = new Map();
                surveyArray.forEach(survey => surveys.set(survey.name, survey));
                set((state) => ({ surveys }));
            }
            else {
                console.error('Failed to get the surveys.', resp);
            }
        }
        catch (error) {
            console.error('Failed to get the surveys.', error);
            if (error.name === 'RunResponseError' &&
                error.response.status === 401) {
                console.error('Received 401, logging out.');
            }
            throw error;
        }
    },
    createSurvey: async (name, form) => {
        const { growthRunUrl } = get();
        const { token } = iamStore.getState();
        try {
            const resp = await requestDatalayerAPI({
                url: `${growthRunUrl}/api/growth/v1/surveys`,
                method: 'POST',
                body: {
                    name,
                    form,
                },
                token,
            });
            if (resp.success && resp.survey) {
                const survey = asSurvey(resp.survey);
                const surveys = get().surveys;
                if (surveys) {
                    surveys.set(survey.name, survey);
                    set((state) => ({ surveys }));
                }
                else {
                    set((state) => ({
                        surveys: new Map([[survey.name, survey]]),
                    }));
                }
            }
            else {
                console.error('Failed to create the survey.', resp);
            }
        }
        catch (error) {
            console.error('Failed to create the survey.', error);
            if (error.name === 'RunResponseError' &&
                error.response.status === 401) {
                console.error('Received 401, logging out.');
            }
            throw error;
        }
    },
}));
coreStore.subscribe((state, prevState) => {
    if (state.configuration.successRunUrl &&
        state.configuration.successRunUrl !== prevState.configuration.successRunUrl) {
        const growthRunUrl = state.configuration.growthRunUrl;
        console.log(`Updating growthRunUrl with new value ${growthRunUrl}`);
        surveysStore.setState({ growthRunUrl });
    }
});
export function useSurveysStore(selector) {
    return useStore(surveysStore, selector);
}
export default useSurveysStore;
