"use server";

import { validateRequest } from "@/server/auth";
import { UserRole } from "@/server/auth/permissions";
import { db } from "@/server/db";
import { users } from "@/server/db/schema";
import { IS, IS_NOT, guard } from "@/utils/guard";
import strings from "@/utils/strings";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

/**
 * Deletes a user from the database
 * @param userId User ID to delete
 * @param path Path to revalidate
 */
export async function deleteUser(userId: string, path?: 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,
		};
	}

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

	if (!targetUser) {
		return {
			error: "Benutzer nicht gefunden",
		};
	}

	if (guard(targetUser, IS, UserRole.ADMIN)) {
		return {
			error: "Admins können nicht gelöscht werden.",
		};
	}

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

	revalidatePath(path ?? "/admin/users");
}
