export type DraftType = 'create' | 'edit';

export type DraftStore<D> = {
    save(type: DraftType, data: D, userId?: number, extraId?: number): boolean;
    load(type: DraftType, userId?: number, extraId?: number): D | null;
    clear(type: DraftType, userId?: number, extraId?: number): void;
};

export function createDraftStore<D>(prefix: string): DraftStore<D> {
    function getKey(
        type: DraftType,
        userId?: number,
        extraId?: number,
    ): string {
        if (type === 'edit' && extraId) {
            return `${prefix}-edit-${userId ?? 'anon'}-${extraId}`;
        }

        return `${prefix}-create-${userId ?? 'anon'}`;
    }

    return {
        save(type, data, userId, extraId) {
            if (type !== 'create') {
                return false;
            }

            try {
                const key = getKey(type, userId, extraId);
                localStorage.setItem(key, JSON.stringify(data));

                return true;
            } catch {
                return false;
            }
        },

        load(type, userId, extraId) {
            try {
                const key = getKey(type, userId, extraId);
                const raw = localStorage.getItem(key);

                if (!raw) {
                    return null;
                }

                return JSON.parse(raw) as D;
            } catch {
                return null;
            }
        },

        clear(type, userId, extraId) {
            try {
                const key = getKey(type, userId, extraId);
                localStorage.removeItem(key);
            } catch {
                // ignore
            }
        },
    };
}
