import { Database } from "bun:sqlite";
import { SCHEMA } from "./schema";

export function createDatabase(path: string): Database {
	const db = new Database(path, { create: true });
	db.run("PRAGMA journal_mode = WAL");
	db.exec(SCHEMA);
	return db;
}

export interface ThreadRow {
	threadId: string;
	subject: string;
	authors: string;
	totalMessages: number;
	tags: string;
	timestamp: number;
	accountId: string;
}

export interface MessageRow {
	messageId: string;
	threadId: string;
	fromHeader: string;
	toHeader: string;
	subject: string;
	date: string;
	inReplyTo: string;
	body: string;
	tags: string;
	timestamp: number;
	accountId: string;
}

export function insertThread(db: Database, thread: ThreadRow): void {
	db.prepare(`
		INSERT OR REPLACE INTO threads
		(thread_id, account_id, subject, authors, total_messages, tags, timestamp)
		VALUES ($threadId, $accountId, $subject, $authors, $totalMessages, $tags, $timestamp)
	`).run({
		$threadId: thread.threadId,
		$accountId: thread.accountId,
		$subject: thread.subject,
		$authors: thread.authors,
		$totalMessages: thread.totalMessages,
		$tags: thread.tags,
		$timestamp: thread.timestamp,
	});
}

export function insertMessage(db: Database, msg: MessageRow): void {
	db.prepare(`
		INSERT OR REPLACE INTO messages
		(message_id, thread_id, account_id, from_header, to_header, subject, date, in_reply_to, body, tags, timestamp)
		VALUES ($messageId, $threadId, $accountId, $fromHeader, $toHeader, $subject, $date, $inReplyTo, $body, $tags, $timestamp)
	`).run({
		$messageId: msg.messageId,
		$threadId: msg.threadId,
		$accountId: msg.accountId,
		$fromHeader: msg.fromHeader,
		$toHeader: msg.toHeader,
		$subject: msg.subject,
		$date: msg.date,
		$inReplyTo: msg.inReplyTo,
		$body: msg.body,
		$tags: msg.tags,
		$timestamp: msg.timestamp,
	});
}

export function getThreads(db: Database, accountId: string): ThreadRow[] {
	return db.prepare(`
		SELECT thread_id as threadId, subject, authors, total_messages as totalMessages,
		       tags, timestamp, account_id as accountId
		FROM threads
		WHERE account_id = $accountId
		ORDER BY timestamp DESC
	`).all({ $accountId: accountId }) as ThreadRow[];
}

export function getMessagesForThread(db: Database, threadId: string): MessageRow[] {
	return db.prepare(`
		SELECT message_id as messageId, thread_id as threadId, from_header as fromHeader,
		       to_header as toHeader, subject, date, in_reply_to as inReplyTo, body, tags,
		       timestamp, account_id as accountId
		FROM messages
		WHERE thread_id = $threadId
		ORDER BY timestamp ASC
	`).all({ $threadId: threadId }) as MessageRow[];
}
