import { type IDBPDatabase, openDB } from "idb";
import type { CalendarEvent } from "@/lib/types";

const DB_NAME = "LocalCalEvents";
const DB_VERSION = 1;
const EVENTS_STORE = "events";

let dbPromise: Promise<IDBPDatabase> | null = null;

function getDB() {
	if (!dbPromise) {
		dbPromise = openDB(DB_NAME, DB_VERSION, {
			upgrade(db) {
				if (!db.objectStoreNames.contains(EVENTS_STORE)) {
					const store = db.createObjectStore(EVENTS_STORE, { keyPath: "id" });
					store.createIndex("start", "start");
					store.createIndex("title", "title");
				}
			},
		});
	}
	return dbPromise;
}

export async function saveEvent(event: CalendarEvent): Promise<void> {
	const db = await getDB();
	await db.put(EVENTS_STORE, event);
}

export async function getEvents(): Promise<CalendarEvent[]> {
	const db = await getDB();
	return db.getAll(EVENTS_STORE);
}

export async function getEvent(id: string): Promise<CalendarEvent | undefined> {
	const db = await getDB();
	return db.get(EVENTS_STORE, id);
}

export async function deleteEvent(id: string): Promise<void> {
	const db = await getDB();
	await db.delete(EVENTS_STORE, id);
}

export async function updateEvent(event: CalendarEvent): Promise<void> {
	const db = await getDB();
	await db.put(EVENTS_STORE, event);
}

export async function getEventsByDateRange(
	startDate: string,
	endDate: string,
): Promise<CalendarEvent[]> {
	const db = await getDB();
	const tx = db.transaction(EVENTS_STORE, "readonly");
	const index = tx.store.index("start");
	const events = await index.getAll(IDBKeyRange.bound(startDate, endDate));
	await tx.done;
	return events;
}

export async function clearEvents(): Promise<void> {
	const db = await getDB();
	await db.clear(EVENTS_STORE);
}
