// BaseDBStore.js
import IndexedDBHelper from '@/common/IndexedDBHelper.js'
// import UniStorageHelper from '../common/UniStorageHelper'
import useChatGroupDBStore from '@/stores/userChatGroupStore'
import config from '@/config'

class BaseStore {
    db = null
    isDBReady = false
    dbName = 'BrowsingHistory' //  'AppMainDB'
    initPromise = null

    constructor() {
        this.initPromise = this.checkAndInitDB()
    }

    async getDB() {
        if (!this.initPromise) {
            this.initPromise = this.checkAndInitDB();
        }
        await this.initPromise; // 等待初始化完成
        return this.db;
    }

    async checkAndInitDB() {
        if (config.OnlyUseCachedDB) {
            return this.initDB()
        }
        const localVersion = uni.getStorageSync('indexedDBVersion') || 1
        console.log('DBVersion: ', localVersion, config.DBversion)
        if (localVersion === config.DBversion) {
            return this.initDB() // 🟢 记得加 return
        } else {
            console.log('清空本地数据库')
            await this.clearDB() // 🟢 建议用 await
            uni.setStorageSync('indexedDBVersion', config.DBversion);
            return this.initDB(); // 🟢 记得加 return
        }
    }

    initDB() {
        // // #ifdef H5
        this.db = new IndexedDBHelper(this.dbName, config.DBversion);
        // // #endif

        return this.db.openDB([{
                name: 'record',
                keyPath: "id",
                autoIncrement: true,
            },
            {
                name: 'messageGroup',
                keyPath: "id",
                autoIncrement: true,
            },
            {
                name: 'messages',
                keyPath: "id",
                autoIncrement: true,
                indexes: [{
                    name: 'parentGroupId',
                    key: 'parentGroupId',
                    unique: false
                }]
            },
            {
                name: 'api_cache',
                keyPath: "cacheKey", // 使用 URL+参数 作为主键
                indexes: []
            }
        ]).then(async () => {
            // 这里原来的逻辑保留
            if (useChatGroupDBStore) {
                useChatGroupDBStore().init()
            }
            this.isDBReady = true
            return this.db;
        });
    }

    async clearDB() {
        return new Promise((resolve, rejetc) => {
            new IndexedDBHelper().deleteDB(this.dbName).then(() => {
                resolve()
            })
        })
    }
}

const baseDB = new BaseStore()
export default baseDB