
import { useDataStore } from "~/stores/data"

export const useEntities = (
    relation: string,
) => {

    const dataStore = useDataStore()
    const toast = useToast()
    const router = useRouter()

    const dataType = dataStore.dataTypes[relation]

    const select = async (
        select: string = "*",
        sortColumn: string | null = null,
        ascending: boolean = false,
        noArchivedFiltering: boolean = false
    ) => {

        const res = await useNuxtApp().$api(`/api/resource/${relation}`, {
            method: "GET",
            params: {
                select,
                sort: sortColumn || undefined,
                asc: ascending
            }
        })

        let data = res || []

        if (dataType && dataType.isArchivable && !noArchivedFiltering) {
            data = data.filter((i: any) => !i.archived)
        }

        return data
    }


    const selectPaginated = async (options: {
        select?: string
        filters?: Record<string, any>
        sort?: { field: string; direction?: 'asc' | 'desc' }[]
        page?: number
        limit?: number
        includeArchived?: boolean
        noPagination?: boolean,
        search?: string,
        searchColumns?: string[],
        distinctColumns?: string[],
    }): Promise<{ data: any[]; meta: any }> => {
        const {
            select = '*',
            filters = {},
            sort = [],
            page = 1,
            limit = 25,
            includeArchived = false,
            noPagination = false,
            search,
            searchColumns = [],
            distinctColumns = [],
        } = options

        const queryParams: Record<string, any> = {
            select,
            page,
            limit,
            noPagination: noPagination ? 'true' : undefined
        }

        // --- 🔍 Search-Parameter (optional) ---
        if (search && search.trim().length > 0) {
            queryParams.search = search.trim()
        }
        if (searchColumns.length > 0) queryParams.searchColumns = searchColumns.join(',')
        if (distinctColumns.length > 0) queryParams.distinctColumns = distinctColumns.join(',')


        // --- Sortierung ---
        if (sort.length > 0) {
            queryParams.sort = sort
                .map(s => `${s.field}:${s.direction || 'asc'}`)
                .join(',')
        }

        // --- Filter ---
        for (const [key, value] of Object.entries(filters)) {
            if (Array.isArray(value)) {
                queryParams[`filter[${key}]`] = value.join(',')
            } else {
                queryParams[`filter[${key}]`] = value
            }
        }

        const response = await useNuxtApp().$api(`/api/resource/${relation}/paginated`, {
            method: 'GET',
            params: queryParams
        })

        if (!response) {
            return { data: [], meta: null }
        }

        let data = response.data || []
        const meta = response.queryConfig || {}

        // --- Optional: Archivierte ausblenden ---
        if (!includeArchived) {
            data = data.filter((i: any) => !i.archived)
        }

        return { data, meta }
    }

    const selectSpecial = async (
        select: string = "*",
        sortColumn: string | null = null,
        ascending: boolean = false,
    ) => {

        const res = await useNuxtApp().$api(`/api/resource-special/${relation}`, {
            method: "GET",
            params: {
                select,
                sort: sortColumn || undefined,
                asc: ascending
            }
        })

        return res || []
    }

    const selectSingle = async (
        idToEq: string | number,
        select: string = "*",
        withInformation: boolean = true
    ) => {
        if (!idToEq) return null

        const res = await useNuxtApp().$api(withInformation ? `/api/resource/${relation}/${idToEq}` : `/api/resource/${relation}/${idToEq}/true`, {
            method: "GET",
            params: { select }
        })

        return res
    }

    const create = async (
        payload: Record<string, any>,
        noRedirect: boolean = false
    ) => {


        const res = await useNuxtApp().$api(`/api/resource/${relation}`, {
            method: "POST",
            body: payload
        })

        toast.add({title: `${dataType.labelSingle} hinzugefügt`})
        if(dataType.redirect && !noRedirect) {
            if(dataType.isStandardEntity) {
                await router.push(dataType.redirectToList ? `/standardEntity/${relation}` : `/standardEntity/${relation}/show/${res.id}`)
            } else {
                await router.push(dataType.redirectToList ? `/${relation}` : `/${relation}/show/${res.id}`)
            }
        }
        //modal.close() TODO: Modal Close wenn in Modal


        return res
    }

    const update = async (
        id: string | number,
        payload: Record<string, any>,
        noRedirect: boolean = false
    ) => {
        const res = await useNuxtApp().$api(`/api/resource/${relation}/${id}`, {
            method: "PUT",
            body: payload
        })

        toast.add({title: `${dataType.labelSingle} geändert`})
        if(dataType.redirect && !noRedirect) {
            if(dataType.isStandardEntity) {
                await router.push(dataType.redirectToList ? `/standardEntity/${relation}` : `/standardEntity/${relation}/show/${res.id}`)
            } else {
                await router.push(dataType.redirectToList ? `/${relation}` : `/${relation}/show/${res.id}`)
            }
        }
        //modal.close() TODO: Modal Close wenn in Modal


        return res
    }

    /**
     * Soft Delete = archived = true
     */
    const archive = async (
        id: string | number
    ) => {
        const res = await useNuxtApp().$api(`/api/resource/${relation}/${id}`, {
            method: "PUT",
            body: { archived: true }
        })
        navigateTo(dataType.isStandardEntity ? `/standardEntity/${relation}` : `/${relation}`)

        return res

    }

    return {select, create, update, archive, selectSingle, selectSpecial, selectPaginated}
}





