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

const getAllPlantSection = async (queryParams) => {
    try {
        // Ensure queryParams is URLSearchParams object
        const params = queryParams instanceof URLSearchParams ? queryParams : new URLSearchParams(queryParams);

        const response = await SendRequest({
            method: 'get',
            prefix: `plant-sub-section?${params.toString()}`,
        });
        console.log('getAllPlantSection response:', response);
        console.log('Query params:', params.toString());

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

        // Check if backend returns paginated data
        if (response.paging) {
            // Extract total_data from first record, or fallback to total_limit or rows
            const totalData = response.data?.[0]?.total_data || response.paging.total_limit || response.rows || response.data?.length || 0;

            // Use total_limit as total count, handle 0 values for page/limit
            const currentPage = response.paging.current_page || 1;
            const currentLimit = response.paging.current_limit || 10;
            const totalPages = response.paging.total_page || Math.ceil(totalData / currentLimit);

            return {
                status: response.statusCode || 200,
                data: {
                    data: response.data || [],
                    paging: {
                        page: currentPage,
                        limit: currentLimit,
                        total: totalData,
                        page_total: totalPages
                    },
                    total: totalData
                }
            };
        }

        // Fallback: If backend returns all data without pagination (old behavior)
        const parsedParams = Object.fromEntries(params);
        const currentPage = parseInt(parsedParams.page) || 1;
        const currentLimit = parseInt(parsedParams.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('getAllPlantSection error:', error);
        return {
            status: 500,
            data: {
                data: [],
                paging: {
                    page: 1,
                    limit: 10,
                    total: 0,
                    page_total: 0
                },
                total: 0
            },
            error: error.message
        };
    }
};

const getPlantSectionById = async (id) => {
    const response = await SendRequest({
        method: 'get',
        prefix: `plant-sub-section/${id}`,
    });
    return response.data;
};

const createPlantSection = async (queryParams) => {
    const response = await SendRequest({
        method: 'post',
        prefix: `plant-sub-section`,
        params: queryParams,
    });
    console.log('createPlantSection full response:', response);
    console.log('createPlantSection payload sent:', queryParams);

    // Check if response has error flag
    if (response.error) {
        return {
            statusCode: response.statusCode || 500,
            data: null,
            message: response.message || 'Request failed',
            rows: 0
        };
    }

    // Backend returns: { statusCode, message, rows, data: [plantSection_object] }
    return {
        statusCode: response.statusCode || 200,
        data: response.data?.[0] || response.data,
        message: response.message,
        rows: response.rows
    };
};

const updatePlantSection = async (plant_section_id, queryParams) => {
    const response = await SendRequest({
        method: 'put',
        prefix: `plant-sub-section/${plant_section_id}`,
        params: queryParams,
    });
    console.log('updatePlantSection full response:', response);
    console.log('updatePlantSection payload sent:', queryParams);

    // Check if response has error flag
    if (response.error) {
        return {
            statusCode: response.statusCode || 500,
            data: null,
            message: response.message || 'Request failed',
            rows: 0
        };
    }

    // Backend returns: { statusCode, message, rows, data: [plantSection_object] }
    return {
        statusCode: response.statusCode || 200,
        data: response.data?.[0] || response.data,
        message: response.message,
        rows: response.rows
    };
};

const deletePlantSection = async (queryParams) => {
    const response = await SendRequest({
        method: 'delete',
        prefix: `plant-sub-section/${queryParams}`,
    });
    console.log('deletePlantSection full response:', response);

    // Check if response has error flag
    if (response.error) {
        return {
            statusCode: response.statusCode || 500,
            data: null,
            message: response.message || 'Request failed',
            rows: 0
        };
    }

    // Backend returns: { statusCode, message, rows: null, data: true }
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message,
        rows: response.rows
    };
};

export { getAllPlantSection, getPlantSectionById, createPlantSection, updatePlantSection, deletePlantSection };
