import {defineStore} from 'pinia'

type historyListType = {
    text: string
    time: number
}

export const useSearchStore = defineStore(
    'searchStore',
    () => {
        const historyList = ref<historyListType[]>([])

        function setHistoryList(keyword: string) {
            const historyListCopy = [...historyList.value]
            let index = historyListCopy.findIndex((item) => item.text === keyword)

            if (index === 0) {
                return
            }

            if (index > 0) {
                historyListCopy.splice(index, 1)
                historyListCopy.unshift({
                    text: keyword,
                    time: new Date().getTime(),
                })
            } else {
                historyListCopy.unshift({
                    text: keyword,
                    time: new Date().getTime(),
                })
            }

            historyList.value = historyListCopy
        }


        return {
            historyList,
            setHistoryList,
        }
    },
    {
        persist: true,
    },
)
