import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface ServerSettingEntry<T = unknown> {
    /** 是否加载中 */
    loading: boolean;
    /** 错误信息（可选） */
    error?: string;
    /** 解析后的配置值 */
    value?: T;
}

export interface ServerSettingState {
    /** 以 code 为 key 存放配置 */
    byCode: Record<string, ServerSettingEntry<any>>;
}

const initialState: ServerSettingState = {
    byCode: {},
};

export const serverSettingSlice = createSlice({
    name: 'serverSetting',
    initialState,
    reducers: {
        setLoading(state, action: PayloadAction<{ code: string; loading: boolean }>) {
            const { code, loading } = action.payload;
            const current = state.byCode[code] || {};
            state.byCode[code] = { ...current, loading, error: loading ? undefined : current.error };
        },
        setValue(state, action: PayloadAction<{ code: string; value: any }>) {
            const { code, value } = action.payload as { code: string; value: unknown };
            const current = state.byCode[code] || {};
            state.byCode[code] = { ...current, loading: false, error: undefined, value };
        },
        setError(state, action: PayloadAction<{ code: string; error: string }>) {
            const { code, error } = action.payload;
            const current = state.byCode[code] || {};
            state.byCode[code] = { ...current, loading: false, error };
        },
        clear(state, action: PayloadAction<{ code: string }>) {
            const { code } = action.payload;
            delete state.byCode[code];
        },
    },
});

export const { setLoading, setValue, setError, clear } = serverSettingSlice.actions;

export default serverSettingSlice.reducer;


