import { openDB, DBSchema, StoreNames } from "idb";

export interface NovelDb extends DBSchema {
  history: {
    value: HistoryItem;
    key: string;
    indexes: {
      uri: string;
      historyUpdateTime: Date;
      historyIsReading: number;
      historyIsFavorite: number;
    };
  };
}

export default function getDb() {
  return openDB<NovelDb>("NovelDit", 3, {
    upgrade(db, oldVersion, newVersion) {
      if (newVersion && newVersion > oldVersion) {
        db.deleteObjectStore("history");
      }

      const historyStore = db.createObjectStore("history", {
        keyPath: "uri",
      });

      historyStore.createIndex("historyUpdateTime", "readTime", {
        unique: false,
      });

      historyStore.createIndex("historyIsReading", ["isReading", "readTime"], {
        unique: false,
      });

      historyStore.createIndex("historyIsFavorite", "isFavorite", {
        unique: false,
      });
    },
  });
}
