import { describe, expect, test, beforeEach } from "bun:test";
import { createDatabase, insertThread, insertMessage, getThreads, getMessagesForThread } from "./index";
import type { Database } from "bun:sqlite";

let db: Database;

beforeEach(() => {
	db = createDatabase(":memory:");
});

describe("threads", () => {
	test("insert and retrieve threads", () => {
		insertThread(db, {
			threadId: "t001",
			subject: "Q1 Planning",
			authors: "Alice, Bob",
			totalMessages: 3,
			tags: "inbox,unread",
			timestamp: 1709884532,
			accountId: "personal",
		});

		const threads = getThreads(db, "personal");
		expect(threads).toHaveLength(1);
		expect(threads[0].threadId).toBe("t001");
		expect(threads[0].subject).toBe("Q1 Planning");
	});
});

describe("messages", () => {
	test("insert and retrieve messages for a thread", () => {
		insertMessage(db, {
			messageId: "msg001@example.com",
			threadId: "t001",
			fromHeader: "Alice <alice@example.com>",
			toHeader: "user@example.com",
			subject: "Q1 Planning",
			date: "2024-03-08T10:15:32+01:00",
			inReplyTo: "",
			body: "Hey, let's plan Q1.",
			tags: "inbox,unread",
			timestamp: 1709884532,
			accountId: "personal",
		});

		const messages = getMessagesForThread(db, "t001");
		expect(messages).toHaveLength(1);
		expect(messages[0].messageId).toBe("msg001@example.com");
		expect(messages[0].body).toBe("Hey, let's plan Q1.");
	});
});
