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

const applicationListEndpoint = `${baseUrlApplication}/application/list/all`;
const applicationListAvailableEndpoint = `${baseUrlApplication}/application/list/available`;
const applicationListAppendedEndpoint = `${baseUrlApplication}/application/list/appended`;
const applicationRegisterServiceEndpoint = `${baseUrlApplication}/application/register/service`;
const applicationUnregisterServiceEndpoint = `${baseUrlApplication}/application/unregister/service`;

const applicationUpdateEndpoint = `${baseUrlApplication}/application/update`;
const applicationCreateEndpoint = `${baseUrlApplication}/application/create`;
const applicationDeleteEndpoint = `${baseUrlApplication}/application/delete`;

interface AppendApplicationToService {
    application_uu_id: string;
    service_uu_id: string;
}

interface RemoveApplicationFromService extends AppendApplicationToService { }


async function listApplicationsAvailable(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(
            applicationListAvailableEndpoint,
            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) {
        console.error("Error fetching events list:", error);
        return {
            data: [],
            pagination: defaultPaginationResponse,
        };
    }
}

async function listApplicationsAppended(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(
            applicationListAppendedEndpoint,
            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 listAllApplications(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
    try {
        const requestBody = {
            page: payload.page,
            size: payload.size,
            order_field: payload.orderField,
            order_type: payload.orderType,
            query: payload.query,
        };


        const response = await fetchDataWithToken(
            applicationListEndpoint,
            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 appendApplicationToService(payload: AppendApplicationToService) {
    try {
        const response = await fetchDataWithToken(
            applicationRegisterServiceEndpoint,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202 ? response.data : null;
    } catch (error) {
        return null;
    }
}

async function removeApplicationFromService(payload: RemoveApplicationFromService) {
    try {
        const response = await fetchDataWithToken(
            applicationUnregisterServiceEndpoint,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202 ? response.data : null;
    } catch (error) {
    }
}

async function createApplication(payload: any) {
    try {
        const response = await fetchDataWithToken(
            applicationCreateEndpoint,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202
            ? response.data
            : null;
    } catch (error) {
        console.error("Error creating application:", error);
        return null;
    }
}

async function updateApplication(payload: any, uuId: string) {
    try {
        const response = await fetchDataWithToken(
            `${applicationUpdateEndpoint}/${uuId}`,
            payload,
            "POST",
            false
        );
        return response?.status === 200 || response?.status === 202
            ? response.data
            : null;
    } catch (error) {
        console.error("Error updating application:", error);
        return null;
    }
}

async function deleteApplication(uuId: string) {
    try {
        const response = await fetchDataWithToken(
            `${applicationDeleteEndpoint}/${uuId}`,
            {},
            "DELETE",
            false
        );
        return response?.status === 200 || response?.status === 202
            ? response.data
            : null;
    } catch (error) {
        console.error("Error deleting application:", error);
        return null;
    }
}

export {
    listApplicationsAvailable,
    listApplicationsAppended,
    listAllApplications,
    appendApplicationToService,
    removeApplicationFromService,
    createApplication,
    updateApplication,
    deleteApplication,
};
