import { beforeEach, describe, expect, it } from "bun:test";
import { globalItems } from "../../src/db/schema.ts";
import {
	createCandidate,
	createThread,
	deleteCandidate,
	deleteThread,
	getAllThreads,
	getThreadWithCandidates,
	reorderCandidates,
	resolveThread,
	updateCandidate,
	updateThread,
} from "../../src/server/services/thread.service.ts";
import { createSecondTestUser, createTestDb } from "../helpers/db.ts";

describe("Thread Service", () => {
	let db: any;
	let userId: number;

	beforeEach(async () => {
		({ db, userId } = await createTestDb());
	});

	describe("createThread", () => {
		it("creates thread with name, returns thread with id/status/timestamps", async () => {
			const thread = await createThread(db, userId, {
				name: "New Tent",
				categoryId: 1,
			});

			expect(thread).toBeDefined();
			expect(thread.id).toBeGreaterThan(0);
			expect(thread.name).toBe("New Tent");
			expect(thread.status).toBe("active");
			expect(thread.resolvedCandidateId).toBeNull();
			expect(thread.createdAt).toBeDefined();
			expect(thread.updatedAt).toBeDefined();
		});
	});

	describe("getAllThreads", () => {
		it("returns active threads with candidateCount and price range", async () => {
			const thread = await createThread(db, userId, {
				name: "Backpack Options",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Pack A",
				categoryId: 1,
				priceCents: 20000,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Pack B",
				categoryId: 1,
				priceCents: 35000,
			});

			const threads = await getAllThreads(db, userId);
			expect(threads).toHaveLength(1);
			expect(threads[0].name).toBe("Backpack Options");
			expect(threads[0].candidateCount).toBe(2);
			expect(threads[0].minPriceCents).toBe(20000);
			expect(threads[0].maxPriceCents).toBe(35000);
		});

		it("excludes resolved threads by default", async () => {
			const _t1 = await createThread(db, userId, {
				name: "Active Thread",
				categoryId: 1,
			});
			const t2 = await createThread(db, userId, {
				name: "Resolved Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, t2.id, {
				name: "Winner",
				categoryId: 1,
			});
			await resolveThread(db, userId, t2.id, candidate.id);

			const active = await getAllThreads(db, userId);
			expect(active).toHaveLength(1);
			expect(active[0].name).toBe("Active Thread");
		});

		it("includes resolved threads when includeResolved=true", async () => {
			const _t1 = await createThread(db, userId, {
				name: "Active Thread",
				categoryId: 1,
			});
			const t2 = await createThread(db, userId, {
				name: "Resolved Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, t2.id, {
				name: "Winner",
				categoryId: 1,
			});
			await resolveThread(db, userId, t2.id, candidate.id);

			const all = await getAllThreads(db, userId, true);
			expect(all).toHaveLength(2);
		});
	});

	describe("getThreadWithCandidates", () => {
		it("returns thread with nested candidates array including category info", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Tent A",
				categoryId: 1,
				weightGrams: 1200,
				priceCents: 30000,
			});

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result).toBeDefined();
			expect(result?.name).toBe("Tent Options");
			expect(result?.candidates).toHaveLength(1);
			expect(result?.candidates[0].name).toBe("Tent A");
			expect(result?.candidates[0].categoryName).toBe("Uncategorized");
			expect(result?.candidates[0].categoryIcon).toBeDefined();
		});

		it("returns null for non-existent thread", async () => {
			const result = await getThreadWithCandidates(db, userId, 9999);
			expect(result).toBeNull();
		});

		it("includes pros and cons on each candidate", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Tent A",
				categoryId: 1,
				pros: "Lightweight",
				cons: "Pricey",
			});

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result).toBeDefined();
			expect(result?.candidates[0].pros).toBe("Lightweight");
			expect(result?.candidates[0].cons).toBe("Pricey");
		});
	});

	describe("createCandidate", () => {
		it("adds candidate to thread with all item-compatible fields", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Tent A",
				weightGrams: 1200,
				priceCents: 30000,
				categoryId: 1,
				notes: "Ultralight 2-person",
				productUrl: "https://example.com/tent",
			});

			expect(candidate).toBeDefined();
			expect(candidate.id).toBeGreaterThan(0);
			expect(candidate.threadId).toBe(thread.id);
			expect(candidate.name).toBe("Tent A");
			expect(candidate.weightGrams).toBe(1200);
			expect(candidate.priceCents).toBe(30000);
			expect(candidate.categoryId).toBe(1);
			expect(candidate.notes).toBe("Ultralight 2-person");
			expect(candidate.productUrl).toBe("https://example.com/tent");
		});

		it("stores and returns pros and cons", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Tent A",
				categoryId: 1,
				pros: "Lightweight\nGood reviews",
				cons: "Expensive",
			});

			expect(candidate.pros).toBe("Lightweight\nGood reviews");
			expect(candidate.cons).toBe("Expensive");
		});

		it("returns null for pros and cons when not provided", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Tent B",
				categoryId: 1,
			});

			expect(candidate.pros).toBeNull();
			expect(candidate.cons).toBeNull();
		});
	});

	describe("updateCandidate", () => {
		it("updates candidate fields, returns updated candidate", async () => {
			const thread = await createThread(db, userId, {
				name: "Test",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Original",
				categoryId: 1,
			});

			const updated = await updateCandidate(db, userId, candidate.id, {
				name: "Updated Name",
				priceCents: 15000,
			});

			expect(updated).toBeDefined();
			expect(updated?.name).toBe("Updated Name");
			expect(updated?.priceCents).toBe(15000);
		});

		it("returns null for non-existent candidate", async () => {
			const result = await updateCandidate(db, userId, 9999, {
				name: "Ghost",
			});
			expect(result).toBeNull();
		});

		it("can set and clear pros and cons", async () => {
			const thread = await createThread(db, userId, {
				name: "Test",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Original",
				categoryId: 1,
			});

			// Set pros and cons
			const withPros = await updateCandidate(db, userId, candidate.id, {
				pros: "Lightweight",
				cons: "Expensive",
			});
			expect(withPros?.pros).toBe("Lightweight");
			expect(withPros?.cons).toBe("Expensive");

			// Clear pros and cons by setting to empty string
			const cleared = await updateCandidate(db, userId, candidate.id, {
				pros: "",
				cons: "",
			});
			// Empty string stored as-is or null — either is acceptable
			expect(cleared?.pros == null || cleared?.pros === "").toBe(true);
			expect(cleared?.cons == null || cleared?.cons === "").toBe(true);
		});
	});

	describe("deleteCandidate", () => {
		it("removes candidate, returns deleted candidate", async () => {
			const thread = await createThread(db, userId, {
				name: "Test",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "To Delete",
				categoryId: 1,
			});

			const deleted = await deleteCandidate(db, userId, candidate.id);
			expect(deleted).toBeDefined();
			expect(deleted?.name).toBe("To Delete");

			// Verify it's gone
			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result?.candidates).toHaveLength(0);
		});

		it("returns null for non-existent candidate", async () => {
			const result = await deleteCandidate(db, userId, 9999);
			expect(result).toBeNull();
		});
	});

	describe("updateThread", () => {
		it("updates thread name", async () => {
			const thread = await createThread(db, userId, {
				name: "Original",
				categoryId: 1,
			});
			const updated = await updateThread(db, userId, thread.id, {
				name: "Renamed",
			});

			expect(updated).toBeDefined();
			expect(updated?.name).toBe("Renamed");
		});

		it("returns null for non-existent thread", async () => {
			const result = await updateThread(db, userId, 9999, { name: "Ghost" });
			expect(result).toBeNull();
		});
	});

	describe("deleteThread", () => {
		it("removes thread and cascading candidates", async () => {
			const thread = await createThread(db, userId, {
				name: "To Delete",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Candidate",
				categoryId: 1,
			});

			const deleted = await deleteThread(db, userId, thread.id);
			expect(deleted).toBeDefined();
			expect(deleted?.name).toBe("To Delete");

			// Thread and candidates gone
			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result).toBeNull();
		});

		it("returns null for non-existent thread", async () => {
			const result = await deleteThread(db, userId, 9999);
			expect(result).toBeNull();
		});
	});

	describe("candidate status", () => {
		it("createCandidate without status returns a candidate with status 'researching'", async () => {
			const thread = await createThread(db, userId, {
				name: "Test Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "No Status",
				categoryId: 1,
			});

			expect(candidate.status).toBe("researching");
		});

		it("createCandidate with status 'ordered' returns a candidate with status 'ordered'", async () => {
			const thread = await createThread(db, userId, {
				name: "Test Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Ordered Item",
				categoryId: 1,
				status: "ordered",
			});

			expect(candidate.status).toBe("ordered");
		});

		it("updateCandidate can change status from 'researching' to 'ordered'", async () => {
			const thread = await createThread(db, userId, {
				name: "Test Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Status Change",
				categoryId: 1,
			});

			expect(candidate.status).toBe("researching");

			const updated = await updateCandidate(db, userId, candidate.id, {
				status: "ordered",
			});

			expect(updated?.status).toBe("ordered");
		});

		it("updateCandidate can change status from 'ordered' to 'arrived'", async () => {
			const thread = await createThread(db, userId, {
				name: "Test Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Arriving Item",
				categoryId: 1,
				status: "ordered",
			});

			const updated = await updateCandidate(db, userId, candidate.id, {
				status: "arrived",
			});

			expect(updated?.status).toBe("arrived");
		});

		it("getThreadWithCandidates includes status field on each candidate", async () => {
			const thread = await createThread(db, userId, {
				name: "Status Thread",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Candidate A",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "Candidate B",
				categoryId: 1,
				status: "ordered",
			});

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result).toBeDefined();
			expect(result?.candidates).toHaveLength(2);

			const candidateA = result?.candidates.find(
				(c: any) => c.name === "Candidate A",
			);
			const candidateB = result?.candidates.find(
				(c: any) => c.name === "Candidate B",
			);

			expect(candidateA?.status).toBe("researching");
			expect(candidateB?.status).toBe("ordered");
		});
	});

	describe("sort_order ordering", () => {
		it("getThreadWithCandidates returns candidates ordered by sort_order ascending", async () => {
			const thread = await createThread(db, userId, {
				name: "Order Test",
				categoryId: 1,
			});
			const c1 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 1",
				categoryId: 1,
			});
			const c2 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 2",
				categoryId: 1,
			});
			const c3 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 3",
				categoryId: 1,
			});

			// Manually set sort_orders out of creation order using reorderCandidates
			await reorderCandidates(db, userId, thread.id, [c3.id, c1.id, c2.id]);

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result).toBeDefined();
			expect(result?.candidates[0].id).toBe(c3.id);
			expect(result?.candidates[1].id).toBe(c1.id);
			expect(result?.candidates[2].id).toBe(c2.id);
		});

		it("createCandidate assigns sort_order = max existing sort_order + 1000", async () => {
			const thread = await createThread(db, userId, {
				name: "Append Test",
				categoryId: 1,
			});

			// First candidate should get sort_order 1000
			const c1 = await createCandidate(db, userId, thread.id, {
				name: "First",
				categoryId: 1,
			});
			expect(c1.sortOrder).toBe(1000);

			// Second candidate should get sort_order 2000
			const c2 = await createCandidate(db, userId, thread.id, {
				name: "Second",
				categoryId: 1,
			});
			expect(c2.sortOrder).toBe(2000);
		});
	});

	describe("reorderCandidates", () => {
		it("reorderCandidates updates sort_order so querying returns candidates in new order", async () => {
			const thread = await createThread(db, userId, {
				name: "Reorder Test",
				categoryId: 1,
			});
			const c1 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 1",
				categoryId: 1,
			});
			const c2 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 2",
				categoryId: 1,
			});
			const c3 = await createCandidate(db, userId, thread.id, {
				name: "Candidate 3",
				categoryId: 1,
			});

			const result = await reorderCandidates(db, userId, thread.id, [
				c3.id,
				c1.id,
				c2.id,
			]);
			expect(result.success).toBe(true);

			const fetched = await getThreadWithCandidates(db, userId, thread.id);
			expect(fetched?.candidates[0].id).toBe(c3.id);
			expect(fetched?.candidates[1].id).toBe(c1.id);
			expect(fetched?.candidates[2].id).toBe(c2.id);
		});

		it("returns { success: false, error } when thread status is 'resolved'", async () => {
			const thread = await createThread(db, userId, {
				name: "Resolved Thread",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Winner",
				categoryId: 1,
			});
			await resolveThread(db, userId, thread.id, candidate.id);

			const result = await reorderCandidates(db, userId, thread.id, [
				candidate.id,
			]);
			expect(result.success).toBe(false);
			expect(result.error).toBeDefined();
		});

		it("returns { success: false } when thread does not exist", async () => {
			const result = await reorderCandidates(db, userId, 9999, [1, 2]);
			expect(result.success).toBe(false);
		});
	});

	describe("resolveThread", () => {
		it("atomically creates collection item from candidate data and archives thread", async () => {
			const thread = await createThread(db, userId, {
				name: "Tent Decision",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Winner Tent",
				weightGrams: 1200,
				priceCents: 30000,
				categoryId: 1,
				notes: "Best choice",
				productUrl: "https://example.com/tent",
			});

			const result = await resolveThread(db, userId, thread.id, candidate.id);
			expect(result.success).toBe(true);
			expect(result.item).toBeDefined();
			expect(result.item?.name).toBe("Winner Tent");
			expect(result.item?.weightGrams).toBe(1200);
			expect(result.item?.priceCents).toBe(30000);
			expect(result.item?.categoryId).toBe(1);
			expect(result.item?.notes).toBe("Best choice");
			expect(result.item?.productUrl).toBe("https://example.com/tent");

			// Thread should be resolved
			const resolved = await getThreadWithCandidates(db, userId, thread.id);
			expect(resolved?.status).toBe("resolved");
			expect(resolved?.resolvedCandidateId).toBe(candidate.id);
		});

		it("fails if thread is not active", async () => {
			const thread = await createThread(db, userId, {
				name: "Already Resolved",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Winner",
				categoryId: 1,
			});
			await resolveThread(db, userId, thread.id, candidate.id);

			// Try to resolve again
			const result = await resolveThread(db, userId, thread.id, candidate.id);
			expect(result.success).toBe(false);
			expect(result.error).toBeDefined();
		});

		it("fails if candidate is not in thread", async () => {
			const thread1 = await createThread(db, userId, {
				name: "Thread 1",
				categoryId: 1,
			});
			const thread2 = await createThread(db, userId, {
				name: "Thread 2",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread2.id, {
				name: "Wrong Thread",
				categoryId: 1,
			});

			const result = await resolveThread(db, userId, thread1.id, candidate.id);
			expect(result.success).toBe(false);
			expect(result.error).toBeDefined();
		});

		it("fails if candidate not found", async () => {
			const thread = await createThread(db, userId, {
				name: "Test",
				categoryId: 1,
			});
			const result = await resolveThread(db, userId, thread.id, 9999);
			expect(result.success).toBe(false);
			expect(result.error).toBeDefined();
		});
	});

	describe("catalog-linked candidates (globalItemId)", () => {
		async function insertGlobalItem(
			testDb: any,
			data: {
				brand: string;
				model: string;
				weightGrams?: number;
				priceCents?: number;
				imageUrl?: string;
			},
		) {
			const [row] = await testDb.insert(globalItems).values(data).returning();
			return row;
		}

		it("createCandidate with globalItemId stores the value on the candidate row", async () => {
			const gi = await insertGlobalItem(db, {
				brand: "Big Agnes",
				model: "Copper Spur HV UL2",
				weightGrams: 1270,
				priceCents: 44995,
			});
			const thread = await createThread(db, userId, {
				name: "Tent Research",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "placeholder",
				categoryId: 1,
				globalItemId: gi.id,
			});

			expect(candidate).toBeDefined();
			expect(candidate.globalItemId).toBe(gi.id);
		});

		it("getThreadWithCandidates returns globalItemId field on each candidate", async () => {
			const gi = await insertGlobalItem(db, {
				brand: "MSR",
				model: "Hubba Hubba",
				weightGrams: 1540,
			});
			const thread = await createThread(db, userId, {
				name: "Tent Options",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "placeholder",
				categoryId: 1,
				globalItemId: gi.id,
			});

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result?.candidates).toHaveLength(1);
			expect(result?.candidates[0].globalItemId).toBe(gi.id);
		});

		it("getThreadWithCandidates merges global item data for candidates with globalItemId", async () => {
			const gi = await insertGlobalItem(db, {
				brand: "Nemo",
				model: "Tensor",
				weightGrams: 425,
				priceCents: 17995,
			});
			const thread = await createThread(db, userId, {
				name: "Pad Research",
				categoryId: 1,
			});
			await createCandidate(db, userId, thread.id, {
				name: "placeholder",
				categoryId: 1,
				globalItemId: gi.id,
			});

			const result = await getThreadWithCandidates(db, userId, thread.id);
			expect(result?.candidates[0].name).toBe("Nemo Tensor");
			expect(result?.candidates[0].weightGrams).toBe(425);
			expect(result?.candidates[0].priceCents).toBe(17995);
		});

		it("resolveThread with candidate having globalItemId creates a reference item", async () => {
			const gi = await insertGlobalItem(db, {
				brand: "Thermarest",
				model: "NeoAir XLite",
				weightGrams: 340,
				priceCents: 20995,
			});
			const thread = await createThread(db, userId, {
				name: "Pad Decision",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "placeholder",
				categoryId: 1,
				globalItemId: gi.id,
				notes: "Great pad",
			});

			const result = await resolveThread(db, userId, thread.id, candidate.id);
			expect(result.success).toBe(true);
			expect(result.item).toBeDefined();
			expect(result.item?.globalItemId).toBe(gi.id);
			expect(result.item?.name).toBe("Thermarest NeoAir XLite");
			// Reference item should NOT copy weight/price from candidate
			expect(result.item?.weightGrams).toBeNull();
			expect(result.item?.priceCents).toBeNull();
			expect(result.item?.notes).toBe("Great pad");
		});

		it("resolveThread with standalone candidate creates a full data copy item", async () => {
			const thread = await createThread(db, userId, {
				name: "Stove Decision",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "Jetboil Flash",
				categoryId: 1,
				weightGrams: 371,
				priceCents: 10995,
				notes: "Fast boil",
				productUrl: "https://example.com/jetboil",
			});

			const result = await resolveThread(db, userId, thread.id, candidate.id);
			expect(result.success).toBe(true);
			expect(result.item?.globalItemId).toBeNull();
			expect(result.item?.name).toBe("Jetboil Flash");
			expect(result.item?.weightGrams).toBe(371);
			expect(result.item?.priceCents).toBe(10995);
			expect(result.item?.productUrl).toBe("https://example.com/jetboil");
		});

		it("resolveThread reference item has brand+model as fallback name", async () => {
			const gi = await insertGlobalItem(db, {
				brand: "MSR",
				model: "PocketRocket 2",
			});
			const thread = await createThread(db, userId, {
				name: "Stove Research",
				categoryId: 1,
			});
			const candidate = await createCandidate(db, userId, thread.id, {
				name: "placeholder",
				categoryId: 1,
				globalItemId: gi.id,
			});

			const result = await resolveThread(db, userId, thread.id, candidate.id);
			expect(result.item?.name).toBe("MSR PocketRocket 2");
		});
	});

	describe("cross-user isolation", () => {
		it("user cannot see other user's threads", async () => {
			const userId2 = await createSecondTestUser(db);

			await createThread(db, userId, {
				name: "User 1 Thread",
				categoryId: 1,
			});
			const user2Categories = await db.query.categories.findMany({
				where: (cats: any, { eq }: any) => eq(cats.userId, userId2),
			});
			const user2CatId = user2Categories[0].id;
			await createThread(db, userId2, {
				name: "User 2 Thread",
				categoryId: user2CatId,
			});

			const user1Threads = await getAllThreads(db, userId);
			const user2Threads = await getAllThreads(db, userId2);

			expect(user1Threads).toHaveLength(1);
			expect(user1Threads[0].name).toBe("User 1 Thread");
			expect(user2Threads).toHaveLength(1);
			expect(user2Threads[0].name).toBe("User 2 Thread");
		});
	});
});
