import { prisma } from "@/lib/prisma"; import { v4 as uuidv4 } from "uuid"; import type { UserData } from "./types"; export async function findUserByKotosoftId(kotosoftId: string) { return prisma.user.findUnique({ where: { kotosoftId } }); } export async function findUserById(id: string) { return prisma.user.findUnique({ where: { id } }); } export async function findUsersByIds(ids: string[]) { const filtered = ids.filter(Boolean); if (filtered.length === 0) return []; return prisma.user.findMany({ where: { id: { in: filtered } } }); } export async function findOrCreateUser(data: UserData) { const existing = await findUserByKotosoftId(data.kotosoftId); if (existing) return existing; return prisma.user.create({ data: { id: uuidv4(), kotosoftId: data.kotosoftId, email: data.email, firstName: data.firstName, secondName: data.secondName, sex: data.sex, birthDate: data.birthDate ? new Date(data.birthDate) : null, isAdmin: data.isAdmin, }, }); } export async function updateUser(id: string, data: Partial>) { return prisma.user.update({ where: { id }, data: { ...data, ...(data.birthDate ? { birthDate: new Date(data.birthDate) } : {}), }, }); } export async function deleteUser(id: string) { await prisma.page.updateMany({ where: { createdBy: id }, data: { createdBy: null } }); await prisma.page.updateMany({ where: { updatedBy: id }, data: { updatedBy: null } }); await prisma.user.delete({ where: { id } }); }