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_NOT, guard } from "@/utils/guard";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import type { z } from "zod";

/**
 * Updates a user in the database
 * @param userId User ID to update
 * @param data Updated user data
 * @param path Path to revalidate
 */
export async function updateUser(userId: string, data: z.infer<typeof formSchema>, path?: 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();
	}

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

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