import { useState, useCallback } from 'react';

import { userKey } from '@/utils/authUtils';
import { secureLocalStorage as ls } from '@/utils/localUtils';
import { currentUnixTimestamp } from '@/utils/timeUtils';

import { createModel } from '../utils/model/createModel';

interface UserConfigState {
    userConfig: API.UserInfo | null;
}

interface UserConfigModel extends UserConfigState {
    setUserConfig: (data: API.UserInfo | null) => void;
}

function getInitialUserConfig(): UserConfigState {
    const stored = ls.getLocal<API.UserInfo>(userKey);
    if (!stored) return { userConfig: null };
    const notExpired = (stored.accessExpires ?? 0) - currentUnixTimestamp() > 0;
    if (!notExpired) return { userConfig: null };
    return { userConfig: stored };
}

const useUserConfigModel = (): UserConfigModel => {
    const [state, setState] = useState<UserConfigState>(getInitialUserConfig);

    const setUserConfig = useCallback((data: API.UserInfo | null) => {
        setState({ userConfig: data });
    }, []);

    return {
        ...state,
        setUserConfig,
    };
};

export const userConfigModel = createModel(useUserConfigModel, 'userConfig');
