"use server";

import { fetchDataWithToken } from "@/apicalls/api-fetcher";
import { baseUrlApplication } from "@/apicalls/basics";
import { PaginationParams } from "@/apicalls/schemas/list";
import { PaginatedApiResponse, collectPaginationFromApiResponse, defaultPaginationResponse } from "@/app/api/utils/types";

const eventsListAvailableEndpoint = `${baseUrlApplication}/events/list/available`;
const eventsListAppendedEndpoint = `${baseUrlApplication}/events/list/appended`;
const appendEventToServiceEndpoint = `${baseUrlApplication}/events/register/service`;
const removeEventFromServiceEndpoint = `${baseUrlApplication}/events/unregister/service`;

interface AppendEventToService {
    service_uu_id: string;
    event_uu_id: string;
}

interface RemoveEventFromService extends AppendEventToService { }


async function list_events_available(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
    if (!payload.query.service_uu_id__ilike) {
        console.warn('Missing service_uu_id in query parameters');
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    }

    try {
        const requestBody = {
            page: payload.page,
            size: payload.size,
            order_field: payload.orderField,
            order_type: payload.orderType,
            query: payload.query,
        };

        const response = await fetchDataWithToken(
            eventsListAvailableEndpoint,
            requestBody,
            "POST",
            false
        );

        if (response?.status === 200 || response?.status === 202) {
            const responseData = response.data as PaginatedApiResponse<any>;
            return {
                data: responseData.data || [],
                pagination: collectPaginationFromApiResponse(responseData)
            };
        }
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    } catch (error) {
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    }
}

async function list_events_appended(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {

    if (!payload.query.service_uu_id__ilike) {
        console.warn('Missing service_uu_id in query parameters for list_events_appended');
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    }

    try {
        const requestBody = {
            page: payload.page,
            size: payload.size,
            order_field: payload.orderField,
            order_type: payload.orderType,
            query: payload.query,
        };

        console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
        console.log('Full request body:', JSON.stringify(requestBody, null, 2));

        const response = await fetchDataWithToken(
            eventsListAppendedEndpoint,
            requestBody,
            "POST",
            false
        );

        if (response?.status === 200 || response?.status === 202) {
            const responseData = response.data as PaginatedApiResponse<any>;
            console.log('list_events_appended responseData:', JSON.stringify(responseData, null, 2));
            return {
                data: responseData.data || [],
                pagination: collectPaginationFromApiResponse(responseData)
            };
        }
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    } catch (error) {
        console.error("Error fetching events list:", error);
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    }
}

async function appendEventToService(payload: AppendEventToService) {
    try {
        const response = await fetchDataWithToken(
            appendEventToServiceEndpoint,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202 ? response.data : null;
    } catch (error) {
        console.error("Error appending event to service:", error);
    }
}

async function removeEventFromService(payload: RemoveEventFromService) {
    try {
        const response = await fetchDataWithToken(
            removeEventFromServiceEndpoint,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202 ? response.data : null;
    } catch (error) {
        console.error("Error removing event from service:", error);
    }
}

export {
    list_events_available,
    list_events_appended,
    appendEventToService,
    removeEventFromService,
};
