"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 { IS_NOT, guard } from "@/utils/guard";
import strings from "@/utils/strings";
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)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	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)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	if (!printer) {
		return {
			error: "Druckerdaten sind erforderlich.",
		};
	}

	try {
		await db.insert(printers).values(printer);
	} catch (error) {
		return {
			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)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	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)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	if (!data) {
		return {
			error: "Druckerdaten sind erforderlich.",
		};
	}

	try {
		await db.update(printers).set(data).where(eq(printers.id, id));
	} catch (error) {
		return {
			error: "Druckerdaten sind erforderlich.",
		};
	}

	revalidatePath("/");
}

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

	if (guard(user, IS_NOT, UserRole.ADMIN)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	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)) {
		return {
			error: strings.ERROR.PERMISSION,
		};
	}

	try {
		await db.delete(printers).where(eq(printers.id, id));
	} catch (error) {
		if (error instanceof Error) {
			return {
				error: error.message,
			};
		}
		return {
			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)],
			},
		},
	});
}
