import axios from "axios";
import dayjs from "dayjs";

const baseURL = /*"http://192.168.1.129:3333"*/ /*"http://localhost:3333"*/ "https://functions.fedeo.io"

export const useFunctions = () => {

    const getWorkingTimesEvaluationData = async (user_id, startDate, endDate) => {
        // Der neue Endpunkt ist /staff/time/evaluation und erwartet die Benutzer-ID als targetUserId Query-Parameter.

        // Wir bauen den Query-String zusammen.
        const queryParams = new URLSearchParams({
            from: startDate,
            to: endDate,
            targetUserId: user_id, // Die ID wird als targetUserId übergeben
        });

        // Der neue API-Pfad verwendet nur noch den Basis-Endpunkt.
        const url = `/api/staff/time/evaluation?${queryParams.toString()}`;

        // Annahme: useNuxtApp().$api führt den GET-Request aus und liefert die Daten zurück.
        return (await useNuxtApp().$api(url));
    }

    const useNextNumber = async (numberRange) => {

        return (await useNuxtApp().$api(`/api/functions/usenextnumber/${numberRange}`,)).usedNumber


    }


    const useBankingGenerateLink = async (institutionId) => {
        return (await useNuxtApp().$api(`/api/banking/link/${institutionId}`)).link
    }

    const useCreatePDF = async (data,path,type) => {
        const returnData = await useNuxtApp().$api(`/api/functions/pdf/${type}`, {
            method: "POST",
            body: {
                data: data,
                backgroundPath: path,
            }
        })

        console.log(returnData)

        return `data:${returnData.mimeType};base64,${returnData.base64}`

    }

    const useZipCheck = async (zip) => {
        const normalizedZip = String(zip || "").replace(/\D/g, "")
        if (!normalizedZip || normalizedZip.length > 5) {
            return null
        }
        const lookupZip = normalizedZip.padStart(5, "0")

        try {
            const data = await useNuxtApp().$api(`/api/functions/check-zip/${lookupZip}`, {
                method: "GET",
            })
            return {
                ...data,
                zip: String(data?.zip ?? lookupZip).replace(/\D/g, "").padStart(5, "0")
            }
        } catch (e) {
            return null
        }
    }






    const useBankingCheckInstitutions = async (bic) => {

        return await useNuxtApp().$api(`/api/banking/institutions/${bic}`)

    }

    const useBankingListRequisitions = async (reqId) => {

        return await useNuxtApp().$api(`/api/banking/requisitions/${reqId}`)

    }

    const useBankingResolveIban = async (iban) => {
        const normalized = String(iban || "").replace(/\s+/g, "").toUpperCase()
        if (!normalized) return null
        return await useNuxtApp().$api(`/api/banking/iban/${encodeURIComponent(normalized)}`)
    }

    const useBankingStatementSuggestions = async (statementId) => {
        if (!statementId) return { suggestions: [] }
        return await useNuxtApp().$api(`/api/banking/statements/${statementId}/suggestions`)
    }

    const useLiquidityForecast = async (ignoredRecurringKeys = []) => {
        const query = new URLSearchParams()
        if (ignoredRecurringKeys.length) {
            query.set("ignoredRecurringKeys", ignoredRecurringKeys.join(","))
        }

        const suffix = query.toString() ? `?${query.toString()}` : ""
        return await useNuxtApp().$api(`/api/functions/liquidity-forecast${suffix}`)
    }

    return {getWorkingTimesEvaluationData, useNextNumber, useBankingGenerateLink, useZipCheck, useBankingCheckInstitutions, useBankingListRequisitions, useBankingResolveIban, useBankingStatementSuggestions, useLiquidityForecast, useCreatePDF}
}
