import {useDataStore} from "~/stores/data.js";


export const useSupabaseSelect = async (relation,select = '*', sortColumn = null, ascending = true,noArchivedFiltering = false) => {
    const supabase = useSupabaseClient()
    const profileStore = useProfileStore()
    let data = null
    const dataStore = useDataStore()

    const dataType = dataStore.dataTypes[relation]

    if(sortColumn !== null ) {
        data = (await supabase
            .from(relation)
            .select(select)
            .eq("tenant", profileStore.currentTenant)
            .order(sortColumn, {ascending: ascending})).data
    } else {
        data = (await supabase
            .from(relation)
            .select(select)
            .eq("tenant", profileStore.currentTenant)).data
    }

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

    return data
}

export const useSupabaseSelectSingle = async (relation,idToEq,select = '*' ) => {
    const supabase = useSupabaseClient()
    const profileStore = useProfileStore()
    let data = null


    if(idToEq !== null) {
        data = (await supabase
            .from(relation)
            .select(select)
            .eq("tenant", profileStore.currentTenant)
            .eq("id",idToEq)
            .single()).data
    } else {
        data = (await supabase
            .from(relation)
            .select(select)
            .eq("tenant", profileStore.currentTenant)
            .single()).data
    }

    return data
}