"use server";

import type { formSchema } from "@/app/admin/users/form";
import { validateRequest } from "@/server/auth";
import { UserRole } from "@/server/auth/permissions";
import { db } from "@/server/db";
import { users } from "@/server/db/schema";
import { PermissionError } from "@/utils/errors";
import { IS, IS_NOT, guard } from "@/utils/guard";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import type { z } from "zod";

/**
 * @deprecated
 */
export async function updateUser(userId: string, data: z.infer<typeof formSchema>) {
	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();
	}

	await db.update(users).set(data).where(eq(users.id, userId));

	revalidatePath("/admin/users");
}

/**
 * @deprecated
 */
export async function deleteUser(userId: 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();
	}

	const targetUser = await db.query.users.findFirst({
		where: eq(users.id, userId),
	});

	if (!targetUser) {
		throw new Error("Benutzer nicht gefunden");
	}

	if (guard(targetUser, IS, UserRole.ADMIN)) {
		throw new Error("Kann keinen Admin löschen");
	}

	await db.delete(users).where(eq(users.id, userId));

	revalidatePath("/admin/users");
}
