import { type DBSchema, type IDBPDatabase, openDB } from "idb" import { nanoid } from "nanoid" // Constants const DB_NAME = "next-ai-drawio-templates" const DB_VERSION = 1 const STORE_NAME = "templates" // Types export interface Template { id: string title: string prompt: string description?: string createdAt: number updatedAt: number clickCount: number runCount: number lastUsedAt: number pinned: boolean } export type TemplateCreateInput = Pick & Partial< Omit< Template, | "id" | "createdAt" | "updatedAt" | "clickCount" | "runCount" | "lastUsedAt" > > interface TemplateDB extends DBSchema { templates: { key: string value: Template indexes: { "by-updated": number "by-pinned": number "by-run-count": number "by-last-used": number } } } // Default title: first 20 chars of trimmed prompt, with ellipsis if truncated const DEFAULT_TITLE_MAX_LENGTH = 20 export function generateDefaultTitle(prompt: string): string { const trimmed = prompt.trim() if (trimmed.length <= DEFAULT_TITLE_MAX_LENGTH) return trimmed return trimmed.slice(0, DEFAULT_TITLE_MAX_LENGTH).trim() + "..." } // Database singleton let dbPromise: Promise> | null = null async function getDB(): Promise> { if (!dbPromise) { dbPromise = openDB(DB_NAME, DB_VERSION, { upgrade(db, oldVersion) { if (oldVersion < 1) { if (!db.objectStoreNames.contains(STORE_NAME)) { const templateStore = db.createObjectStore(STORE_NAME, { keyPath: "id", }) templateStore.createIndex("by-updated", "updatedAt") templateStore.createIndex("by-pinned", "pinned") templateStore.createIndex("by-run-count", "runCount") templateStore.createIndex("by-last-used", "lastUsedAt") } } }, }) } return dbPromise } // Check if IndexedDB is available export function isIndexedDBAvailable(): boolean { if (typeof window === "undefined") return false try { return "indexedDB" in window && window.indexedDB !== null } catch { return false } } // CRUD Operations export async function getAllTemplates(): Promise { if (!isIndexedDBAvailable()) return [] try { const db = await getDB() const templates = await db.getAll(STORE_NAME) return sortTemplates(templates) } catch (error) { console.error("Failed to get templates:", error) return [] } } export async function getTemplate(id: string): Promise