import { SendRequest } from '../components/Global/ApiRequest';

const getAllDevice = async (queryParams) => {
    const response = await SendRequest({
        method: 'get',
        prefix: `device?${queryParams.toString()}`,
    });
    console.log('getAllDevice response:', response);
    console.log('Query params:', queryParams.toString());

    // Parse query params to get page and limit
    const params = Object.fromEntries(queryParams);
    const currentPage = parseInt(params.page) || 1;
    const currentLimit = parseInt(params.limit) || 10;

    // Backend returns all data, so we need to do client-side pagination
    const allData = response.data || [];
    const totalData = allData.length;

    // Calculate start and end index for current page
    const startIndex = (currentPage - 1) * currentLimit;
    const endIndex = startIndex + currentLimit;

    // Slice data for current page
    const paginatedData = allData.slice(startIndex, endIndex);

    // Transform response to match TableList expected structure
    return {
        status: response.statusCode || 200,
        data: {
            data: paginatedData,
            paging: {
                page: currentPage,
                limit: currentLimit,
                total: totalData,
                page_total: Math.ceil(totalData / currentLimit)
            },
            total: totalData
        }
    };
};

const getDeviceById = async (id) => {
    const response = await SendRequest({
        method: 'get',
        prefix: `device/${id}`,
    });
    return response.data;
};

const createDevice = async (queryParams) => {
    const response = await SendRequest({
        method: 'post',
        prefix: `device`,
        params: queryParams,
    });
    console.log('createDevice full response:', response);
    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message
    };
};

const updateDevice = async (device_id, queryParams) => {
    const response = await SendRequest({
        method: 'put',
        prefix: `device/${device_id}`,
        params: queryParams,
    });
    console.log('updateDevice full response:', response);
    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message
    };
};

const deleteDevice = async (queryParams) => {
    const response = await SendRequest({
        method: 'delete',
        prefix: `device/${queryParams}`,
    });
    console.log('deleteDevice full response:', response);
    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message
    };
};

export { getAllDevice, getDeviceById, createDevice, updateDevice, deleteDevice };
