import { TRPCError } from "@trpc/server";
import { count, desc, eq } from "drizzle-orm";
import { database } from "@/db";
import { libraryFolders, titles } from "@/db/schema";
import { t } from "@/lib/trpc";
import {
	GetAllLibrariesInput,
	GetAllLibrariesOutput,
	GetLibraryTitlesInput,
	GetLibraryTitlesOutput,
} from "@/models/trpc/library";
import { authenticationMiddleware } from "../middleware/authentication";

const libraryProcedure = t.procedure.use(authenticationMiddleware);

export const libraryRouter = t.router({
	getAll: libraryProcedure
		.input(GetAllLibrariesInput)
		.output(GetAllLibrariesOutput)
		.query(async () => {
			const libraries = await database
				.select({
					id: libraryFolders.id,
					name: libraryFolders.name,
					type: libraryFolders.type,
					path: libraryFolders.path,
				})
				.from(libraryFolders)
				.orderBy(libraryFolders.name);

			return libraries;
		}),

	getTitles: libraryProcedure
		.input(GetLibraryTitlesInput)
		.output(GetLibraryTitlesOutput)
		.query(async ({ input }) => {
			const { libraryId, page, limit } = input;

			// Verify library exists
			const library = await database
				.select({ id: libraryFolders.id })
				.from(libraryFolders)
				.where(eq(libraryFolders.id, libraryId))
				.limit(1);

			if (library.length === 0) {
				throw new TRPCError({
					code: "NOT_FOUND",
					message: "Library not found",
				});
			}

			// Get total count
			const totalCountResult = await database
				.select({ count: count() })
				.from(titles)
				.where(eq(titles.libraryFolderId, libraryId));

			const total = totalCountResult[0].count;
			const totalPages = Math.ceil(total / limit);

			// Calculate offset
			const offset = (page - 1) * limit;

			// Get paginated titles
			const titlesData = await database
				.select({
					id: titles.id,
					title: titles.title,
					year: titles.year,
					poster: titles.poster,
					type: titles.type,
				})
				.from(titles)
				.where(eq(titles.libraryFolderId, libraryId))
				.orderBy(desc(titles.createdAt))
				.limit(limit)
				.offset(offset);

			return {
				titles: titlesData,
				pagination: {
					total,
					page,
					limit,
					totalPages,
				},
			};
		}),
});
