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

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

        // Backend response structure:
        // {
        //   statusCode: 200,
        //   data: [...devices],
        //   paging: {
        //     current_page: 1,
        //     current_limit: 10,
        //     total_limit: 50,
        //     total_page: 5
        //   }
        // }

        // Check if backend returns paginated data
        if (response.paging) {
            const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;

            return {
                status: response.statusCode || 200,
                data: {
                    data: response.data || [],
                    paging: {
                        page: response.paging.current_page || 1,
                        limit: response.paging.current_limit || 10,
                        total: totalData,
                        page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
                    },
                    total: totalData
                }
            };
        }

        // Fallback: If backend returns all data without pagination (old behavior)
        const params = Object.fromEntries(queryParams);
        const currentPage = parseInt(params.page) || 1;
        const currentLimit = parseInt(params.limit) || 10;

        const allData = response.data || [];
        const totalData = allData.length;

        // Client-side pagination
        const startIndex = (currentPage - 1) * currentLimit;
        const endIndex = startIndex + currentLimit;
        const paginatedData = allData.slice(startIndex, endIndex);

        return {
            status: response.statusCode || 200,
            data: {
                data: paginatedData,
                paging: {
                    page: currentPage,
                    limit: currentLimit,
                    total: totalData,
                    page_total: Math.ceil(totalData / currentLimit)
                },
                total: totalData
            }
        };
    } catch (error) {
        console.error('getAllDevice error:', error);
        return {
            status: 500,
            data: {
                data: [],
                paging: {
                    page: 1,
                    limit: 10,
                    total: 0,
                    page_total: 0
                },
                total: 0
            },
            error: error.message
        };
    }
};

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);
    console.log('createDevice payload sent:', queryParams);

    // Backend returns: { statusCode, message, rows, data: [device_object] }
    // Check if response is empty array (error from SendRequest)
    if (Array.isArray(response) && response.length === 0) {
        return {
            statusCode: 500,
            data: null,
            message: 'Request failed',
            rows: 0
        };
    }

    // Extract first item from data array
    return {
        statusCode: response.statusCode || 200,
        data: response.data?.[0] || response.data,
        message: response.message,
        rows: response.rows
    };
};

const updateDevice = async (device_id, queryParams) => {
    const response = await SendRequest({
        method: 'put',
        prefix: `device/${device_id}`,
        params: queryParams,
    });
    console.log('updateDevice full response:', response);
    console.log('updateDevice payload sent:', queryParams);

    // Backend returns: { statusCode, message, rows, data: [device_object] }
    // Check if response is empty array (error from SendRequest)
    if (Array.isArray(response) && response.length === 0) {
        return {
            statusCode: 500,
            data: null,
            message: 'Request failed',
            rows: 0
        };
    }

    // Extract first item from data array
    return {
        statusCode: response.statusCode || 200,
        data: response.data?.[0] || response.data,
        message: response.message,
        rows: response.rows
    };
};

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

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