import axios from "axios";
import { Network } from "@/app/types";

const useNetworks = () => {
   
    const addNetwork = (network: Network): Promise<Network> | string => {
        if (!network.name) {
            return 'Network name is required';
        }
        
        return axios.post('/api/sites/networks/add', network)
        .then((response) => {
            return response.data.network;
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    const editNetwork = (network: Network): Promise<string> | string => {
        if (!network.id) {
            return 'Network ID is required';
        }
        if(network.name.length < 1) {
            return 'Network name must be at least 1 character long';
        }
        return axios.post('/api/sites/networks/edit', network)
        .then(() => {
            return "Network edited successfully";
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    const deleteNetwork = (networkId: number): Promise<string> | string => {
        if (!networkId) {
            return 'Network ID is required';
        }
        return axios.delete('/api/sites/networks/delete', {
            params: { networkId }
        })
        .then(() => {
            return "Network deleted successfully";
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    return {
        addNetwork,
        editNetwork,
        deleteNetwork,
    };
};

export default useNetworks;