import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

interface VersionHistoryStore {
    versionHistory: VersionHistory;

    createNewVersion: boolean;

    setCreateNewVersion: (createNewVersion: boolean) => void;

    addVersion: (version: Version) => void;
    setVersions: (versions: Version[]) => void;
    clearVersions: () => void;

    setVersionName: (versionId: string, versionName: string) => void;
    updateVersion: (versionId: string, versionName: string, versionDescription: string) => void;

    getVersionById: (versionId: string) => Version | undefined;
}

export const useVersionHistoryStore = create<VersionHistoryStore>()(
    immer((set, get) => ({
        versionHistory: [],
        selectedVersion: null,
        createNewVersion: false,

        setCreateNewVersion: (createNewVersion: boolean) => {
            set((state) => {
                state.createNewVersion = createNewVersion;
            })
        },

        addVersion: (version: Version) => {
            set((state) => {
                state.versionHistory.unshift(version);
            })
        },

        setVersions: (versions: Version[]) => {
            set((state) => {
                state.versionHistory = versions;
            })
        },

        clearVersions: () => {
            set((state) => {
                state.versionHistory = [];
            })
        },

        setVersionName: (versionId: string, versionName: string) => {
            set((state) => {
                const version = state.versionHistory.find((v) => v.versionId === versionId);
                if (version) {
                    version.versionName = versionName;
                }
            })
        },

        updateVersion: (versionId: string, versionName: string, versionDescription: string) => {
            set((state) => {
                const version = state.versionHistory.find((v) => v.versionId === versionId);
                if (version) {
                    version.versionName = versionName;
                    version.versionDescription = versionDescription;
                }
            })
        },

        getVersionById: (versionId: string) => {
            return get().versionHistory.find((v) => {
                return v.versionId === versionId
            })
        }
    }))
);
