"use server"

import category from "@/models/category"
import healthBeautyProduct from "@/models/healthBeautyProduct "
import homeApplianceProduct from "@/models/homeApplianceProduct"
import mobileAccessoryProducts from "@/models/mobileAccessoryProducts"
import searchedQuarrys from "@/models/searchedQuarrys"
import shoesProduct from "@/models/shoesProduct"
import subCategories from "@/models/subCategories"
import subCategoryPart from "@/models/subCategoryPart"
import { cookies } from 'next/headers'




// Named export
export const  SearchInSubCatParts = async (searchParam) => {
    const getSearchParam = await searchParam
    const allProductsArray = []
    const foundSubCatPartArray = []
    const foundSubCatPartObjectArray = []
    const getAllhomeappliances = await homeApplianceProduct.find()
    const getAllhealthBeautyProduct = await healthBeautyProduct.find()
    const getAllshoesProduct = await shoesProduct.find()
    const getAllmobileAccessoryProducts = await mobileAccessoryProducts.find()
    const categoryResault = await category.find()
    const subCategoriesResault = await subCategories.find()
    const subCategoryPartResault = await subCategoryPart.find()

    if(getAllhomeappliances.length){
        allProductsArray.push(...getAllhomeappliances)
    }
    if(getAllhealthBeautyProduct.length){
        allProductsArray.push(...getAllhealthBeautyProduct)
    }
    if(getAllshoesProduct.length){
        allProductsArray.push(...getAllshoesProduct)
    }
    if(getAllmobileAccessoryProducts.length){
        allProductsArray.push(...getAllmobileAccessoryProducts)
    }

    categoryResault.forEach( subCatPart => {
        const vsta = {subCatPartName:subCatPart.title,subCatPartId:subCatPart._id,subCatPartAllViewsNumbs:0,code:0}
        allProductsArray.forEach((product)=>{
            if((subCatPart._id).toString() === (product.category).toString()){
                vsta.subCatPartAllViewsNumbs=Number(vsta.subCatPartAllViewsNumbs)+Number(product.view)
            }
        })
        foundSubCatPartObjectArray.push(vsta)
    });
    subCategoriesResault.forEach( subCatPart => {
        const vsta = {subCatPartName:subCatPart.title,subCatPartId:subCatPart._id,subCatPartAllViewsNumbs:0,code:1}
        allProductsArray.forEach((product)=>{
            if((subCatPart._id).toString() === (product.subcategory).toString()){
                vsta.subCatPartAllViewsNumbs=Number(vsta.subCatPartAllViewsNumbs)+Number(product.view)
            }
        })
        foundSubCatPartObjectArray.push(vsta)
    });
    subCategoryPartResault.forEach( subCatPart => {
        const vsta = {subCatPartName:subCatPart.title,subCatPartId:subCatPart._id,subCatPartAllViewsNumbs:0,code:2}
        allProductsArray.forEach((product)=>{
            if((subCatPart._id).toString() === (product.subcategorypart).toString()){
                vsta.subCatPartAllViewsNumbs=Number(vsta.subCatPartAllViewsNumbs)+Number(product.view)
            }
        })
        foundSubCatPartObjectArray.push(vsta)
    });
    foundSubCatPartObjectArray.forEach((subCatPart)=>{
        if(subCatPart.subCatPartName.replace(/ /g,'').toLowerCase().search(getSearchParam.replace(/ /g,'').toLowerCase()) !== -1){
            foundSubCatPartArray.push(subCatPart)
        }
    })
    foundSubCatPartArray.sort((a, b) => b.subCatPartAllViewsNumbs - a.subCatPartAllViewsNumbs);
    const foundSubCatPartArraySliced =  foundSubCatPartArray.slice(0,4)
  
    return JSON.stringify(foundSubCatPartArraySliced)

}
  
export const  SearchInBrands = async (searchParamTwo) => {
    const getSearchParamTwo = await searchParamTwo
    const allProductsArray = []
    const getOrigins = []
    const filteredOrigins = []
    const getAllhomeappliances = await homeApplianceProduct.find()
    const getAllhealthBeautyProduct = await healthBeautyProduct.find()
    const getAllshoesProduct = await shoesProduct.find()
    const getAllmobileAccessoryProducts = await mobileAccessoryProducts.find()

    if(getAllhomeappliances.length){
        allProductsArray.push(...getAllhomeappliances)
    }

    if(getAllhealthBeautyProduct.length){
        allProductsArray.push(...getAllhealthBeautyProduct)
    }

    if(getAllshoesProduct.length){
        allProductsArray.push(...getAllshoesProduct)
    }

    if(getAllmobileAccessoryProducts.length){
        allProductsArray.push(...getAllmobileAccessoryProducts)
    }

    allProductsArray.forEach((product)=>{
        const originName = product.origin !== undefined?product.origin:''
        // const extractedText = originName !== undefined?originName.replace(/برند\s*/g, "").replace(/شرکت\s*/g, "").replace(/[A-Za-z]/g, "").replace(/[()]/g, "").trim():"برند"
        originName.replace(/ /g,'').toLowerCase().search(getSearchParamTwo.toLowerCase().replace(/ /g,'')) !== -1 && getOrigins.push({persianBrandName:originName,englishBrandName:product.brand})
    })

    getOrigins.forEach((origin)=>{
        if(filteredOrigins.length){
            const indexResault = filteredOrigins.findIndex((filteredOrigin)=>{
                return filteredOrigin.persianBrandName === origin.persianBrandName
            })
            indexResault == -1?filteredOrigins.push(origin):null
        }else{
            filteredOrigins.push(origin)
        }
    })


    return JSON.stringify(filteredOrigins.slice(0,3))
}


export const  SearchInProducts = async (searchParamThree) => {
    const getSearchParamThree = await searchParamThree
    const allProductsArray = []
    const allProductsFound = []
    const getAllhomeappliances = await homeApplianceProduct.find()
    const getAllhealthBeautyProduct = await healthBeautyProduct.find()
    const getAllshoesProduct = await shoesProduct.find()
    const getAllmobileAccessoryProducts = await mobileAccessoryProducts.find()

    if(getAllhomeappliances.length){
        allProductsArray.push(...getAllhomeappliances)
    }

    if(getAllhealthBeautyProduct.length){
        allProductsArray.push(...getAllhealthBeautyProduct)
    }

    if(getAllshoesProduct.length){
        allProductsArray.push(...getAllshoesProduct)
    }

    if(getAllmobileAccessoryProducts.length){
        allProductsArray.push(...getAllmobileAccessoryProducts)
    }

    allProductsArray.forEach((product)=>{
        const productTitle = product.title
        productTitle.replace(/ /g,'').toLowerCase().search(getSearchParamThree.toLowerCase().replace(/ /g,'')) !== -1 && allProductsFound.push({productTitleName:product.title,productId:product._id,productViewsCount:product.view,productCategoryId:product.category})
    })
    allProductsFound.sort((a, b) => b.productViewsCount - a.productViewsCount);

    return JSON.stringify(allProductsFound.slice(0,5))
}

export const SearchRegistration = async (searchInput,allInfo,typeCode) => {
    
    const getSearchInput = searchInput
    const getAllInfo = allInfo
    const getTypeCode = typeCode
    
    let usersSearchSelectedGot = getTypeCode == 1?getAllInfo.subCatPartName:getTypeCode == 2?getAllInfo.persianBrandName:getTypeCode == 3?getAllInfo.productTitleName:false
    
    const geSearcheMaches = await searchedQuarrys.find({searchParam:getSearchInput})
    if(geSearcheMaches.length){
        const geSearcheMachesSpecific= geSearcheMaches[0]
        const geSearcheMachesSpecificCount= Number(geSearcheMachesSpecific.searchCount)+1
        await searchedQuarrys.findByIdAndUpdate(geSearcheMachesSpecific._id,{searchInfo:[...geSearcheMachesSpecific.searchInfo,getAllInfo],searchCount:geSearcheMachesSpecificCount })
        
    }else{
        const newSaveQuary = new searchedQuarrys({
            searchParam:getSearchInput,
            userSearchSelected:usersSearchSelectedGot,
            searchInfo:getAllInfo,
            searchCount:1
        })
        await newSaveQuary.save()
    }

    const cookieStore = await cookies(); // ✅ await is important
    const cookieValue = cookieStore.get("userSearchedWords")?.value;

    if (!cookieValue){
        const userSearchedWords = []
        userSearchedWords.push(getSearchInput)
        const jsonString = JSON.stringify(userSearchedWords);
        cookieStore.set({
            name: "userSearchedWords",
            value: encodeURIComponent(jsonString),
            path: "/",
            maxAge: 60 * 60 * 24 * 365 * 10, // 1 year
            httpOnly: false,
        });
    }else{
        const userSearchedArrayCookies = JSON.parse(decodeURIComponent(cookieValue))
        !userSearchedArrayCookies.includes(getSearchInput)?userSearchedArrayCookies.push(getSearchInput):null
        cookieStore.set({
            name: "userSearchedWords",
            value: encodeURIComponent(JSON.stringify(userSearchedArrayCookies)),
            path: "/",
            maxAge: 60 * 60 * 24 * 365 * 10, // 1 year
            httpOnly: false,
        });
        
    }

}
export async function deleteUserSearchedWordsCookie() {
    const cookieStore = await cookies(); // ✅ await is important
    cookieStore.set({
        name: "userSearchedWords",
        value: "",
        expires: new Date(0), // Expire immediately
        path: "/"
    });
}





