"use server";

import { validateRequest } from "@/server/auth";
import { UserRole } from "@/server/auth/permissions";
import { db } from "@/server/db";
import { printers, users } from "@/server/db/schema";
import { PermissionError } from "@/utils/errors";
import { IS_NOT, guard } from "@/utils/guard";
import { type InferInsertModel, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

export async function createPrinter(printer: InferInsertModel<typeof printers>) {
	const { user } = await validateRequest();

	if (guard(user, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	const dbUser = await db.query.users.findFirst({
		// biome-ignore lint/style/noNonNullAssertion: guard already checks against null
		where: eq(users.id, user!.id),
	});

	if (guard(dbUser, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	if (!printer) {
		throw new Error("Druckerdaten sind erforderlich.");
	}

	try {
		await db.insert(printers).values(printer);
	} catch (error) {
		throw new Error("Drucker konnte nicht hinzugefügt werden.");
	}

	revalidatePath("/");
}

export async function updatePrinter(id: string, data: InferInsertModel<typeof printers>) {
	const { user } = await validateRequest();

	if (guard(user, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	const dbUser = await db.query.users.findFirst({
		// biome-ignore lint/style/noNonNullAssertion: guard already checks against null
		where: eq(users.id, user!.id),
	});

	if (guard(dbUser, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	if (!data) {
		throw new Error("Druckerdaten sind erforderlich.");
	}

	try {
		await db.update(printers).set(data).where(eq(printers.id, id));
	} catch (error) {
		throw new Error("Drucker konnte nicht aktualisiert werden.");
	}

	revalidatePath("/");
}

export async function deletePrinter(id: string) {
	const { user } = await validateRequest();

	if (guard(user, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	const dbUser = await db.query.users.findFirst({
		// biome-ignore lint/style/noNonNullAssertion: guard already checks against null
		where: eq(users.id, user!.id),
	});

	if (guard(dbUser, IS_NOT, UserRole.ADMIN)) {
		throw new PermissionError();
	}

	try {
		await db.delete(printers).where(eq(printers.id, id));
	} catch (error) {
		if (error instanceof Error) {
			throw new Error(error.message);
		}
		throw new Error("Ein unbekannter Fehler ist aufgetreten.");
	}

	revalidatePath("/");
}

export async function getPrinters() {
	return await db.query.printers.findMany({
		with: {
			printJobs: {
				limit: 1,
				orderBy: (printJobs, { desc }) => [desc(printJobs.startAt)],
			},
		},
	});
}
