import axiosInstance from '../../../../utils/axiosInstance';

const fetchData= async (search, sort, page, limit) => {
    try {
        const response = await axiosInstance.get(`/user/student?search=${search}&sort=${sort}&page=${page}&limit=${limit}`);
        return response.data;
    } catch (error) {
        console.error('Error fetching sections:', error);
        throw error;
    }
};

const getStudentById = async (id) => {
    try {
        const response = await axiosInstance.get(`/student/${id}`);
        return response.data;
    } catch (error) {
        console.error(`Error fetching student with ID ${id}:`, error);
        throw error;
    }
};

const createData = async (studentData) => {
    try {
        const response = await axiosInstance.post(`/admin/register/student`, studentData);
        return response.data;
    } catch (error) {
        console.error('Error adding student:', error);
        throw error;
    }
};

const updateData = async (id, studentData) => {
    try {
        const response = await axiosInstance.put(`/user/update/${id}`, studentData);
        return response.data;
    } catch (error) {
        console.error(`Error updating student with ID ${id}:`, error);
        throw error;
    }
};

const deleteData = async (id) => {
    try {
        const response = await axiosInstance.delete(`/user/delete/${id}`);
        return response.data;
    } catch (error) {
        console.error(`Error deleting student with ID ${id}:`, error);
        throw error;
    }
};

const getTemplate = async () => {
    const configs = {
        headers: {
          Authorization: localStorage.getItem('token')
        },
        responseType: 'blob',
    };
    try {
        const response = await axiosInstance.get(`/user/sendExcelExample`, configs);
        return response.data;
    } catch (error) {
        console.error(`Error get file:`, error);
        throw error;
    }
};

const registerImport = async (file) => {
    try {
        const response = await axiosInstance.post(`/admin/register/student/csv`, file);
        return response.data;
    } catch (error) {
        console.error('Error adding student:', error);
        throw error;
    }
};

export default{
    fetchData,
    getStudentById,
    createData,
    updateData,
    deleteData,
    getTemplate,
    registerImport
};
