import { type DBSchema, type IDBPDatabase, openDB } from "idb" import { nanoid } from "nanoid" import { isIndexedDBAvailable } from "./session-storage" // 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 runCount: number lastUsedAt: number pinned: boolean } export type TemplateCreateInput = Pick & Partial< Omit< Template, "id" | "createdAt" | "updatedAt" | "runCount" | "lastUsedAt" > > interface TemplateDB extends DBSchema { templates: { key: string value: Template } } // 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)) { db.createObjectStore(STORE_NAME, { keyPath: "id" }) } } }, }) } return dbPromise } // 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 createTemplate( input: TemplateCreateInput, ): Promise