"use server" import { prisma } from "@/lib/prisma"; import { artworkSchema } from "@/schemas/artworks/imageSchema"; import { normalizeNames, slugify } from "@/utils/artworkHelpers"; import { z } from "zod/v4"; export async function updateArtwork( values: z.infer, id: string ) { const validated = artworkSchema.safeParse(values); if (!validated.success) { throw new Error("Invalid image data"); } const { name, needsWork, nsfw, published, setAsHeader, altText, description, notes, month, year, creationDate, tagIds, categoryIds, newTagNames, newCategoryNames, } = validated.data; const tagsToCreate = normalizeNames(newTagNames); const categoriesToCreate = normalizeNames(newCategoryNames); const updatedArtwork = await prisma.$transaction(async (tx) => { if(setAsHeader) { await tx.artwork.updateMany({ where: { setAsHeader: true }, data: { setAsHeader: false }, }) } const tagsRelation = tagIds || tagsToCreate.length ? { tags: { set: [], // replace entire relation connect: (tagIds ?? []).map((tagId) => ({ id: tagId })), connectOrCreate: tagsToCreate.map((tName) => ({ where: { name: tName }, create: { name: tName, slug: slugify(tName) }, })), }, } : {}; const categoriesRelation = categoryIds || categoriesToCreate.length ? { categories: { set: [], connect: (categoryIds ?? []).map((catId) => ({ id: catId })), connectOrCreate: categoriesToCreate.map((cName) => ({ where: { name: cName }, create: { name: cName, slug: slugify(cName) }, })), }, } : {}; return tx.artwork.update({ where: { id: id }, data: { name, slug: slugify(name), needsWork, nsfw, published, setAsHeader, altText, description, notes, month, year, creationDate, ...tagsRelation, ...categoriesRelation, } }); }); return updatedArtwork; }