import {useEffect, useState} from "react";
import axios from "axios";
import {GET_CONFIG} from "@/core/data/apiRoutes";
import {ConfigProvider} from "@/lib/app/contexts/config";
import {isValidJson} from "@/core/utils/isValidJson";
import {useRouter} from "next/router";

const ConfigApp = ({children}) => {
    const router = useRouter()
    const [error, setError] = useState(false)
    const [config, setConfig] = useState()

    useEffect(() => {
        const fetchConfig = async () => {
            try {
                const response = await axios(GET_CONFIG)
                let _config = {}
                response.data.data.forEach(item => {
                    _config[item.name] = isValidJson(item.value) ? JSON.parse(item.value) : item.value
                })
                setConfig(_config)
            } catch (error) {
                setError(true)
            }
        }

        fetchConfig()

    }, [router]);

    return (
        <ConfigProvider config={config || {}}>{error ? <>Error request config</> : config && children}</ConfigProvider>)
}

export default ConfigApp