"use server"; import { z } from "zod"; import { getBriefingDoCliente } from "@/lib/briefing-service"; import { db } from "@/lib/db"; const respostaSchema = z.object({ texto: z.string().optional(), complemento: z.string().optional(), selecionadas: z.array(z.string()).optional() }); const salvarRespostasSchema = z.object({ perguntas: z.record(respostaSchema) }); export type SalvarRespostasResult = { ok: boolean; savedAt?: string; message?: string; }; function hasValue(resposta: z.infer) { return Boolean( resposta.texto?.trim() || resposta.complemento?.trim() || (resposta.selecionadas && resposta.selecionadas.length > 0) ); } export async function salvarRespostas( briefingId: string, secaoId: string, valores: unknown ): Promise { const parsed = salvarRespostasSchema.safeParse(valores); if (!parsed.success) { return { ok: false, message: "Dados invalidos para salvar." }; } const briefing = await getBriefingDoCliente(briefingId); if (briefing.status !== "RASCUNHO") { return { ok: false, message: "Este briefing ja foi enviado e nao aceita novas alteracoes." }; } const perguntasDaSecao = await db.pergunta.findMany({ where: { secaoId, ativo: true }, select: { id: true } }); const perguntaIds = new Set(perguntasDaSecao.map((pergunta) => pergunta.id)); await db.$transaction( Object.entries(parsed.data.perguntas) .filter(([perguntaId]) => perguntaIds.has(perguntaId)) .map(([perguntaId, resposta]) => { if (!hasValue(resposta)) { return db.resposta.deleteMany({ where: { briefingId, perguntaId } }); } return db.resposta.upsert({ where: { briefingId_perguntaId: { briefingId, perguntaId } }, update: { texto: resposta.texto?.trim() || null, complemento: resposta.complemento?.trim() || null, selecionadas: resposta.selecionadas?.length ? resposta.selecionadas : null }, create: { briefingId, perguntaId, texto: resposta.texto?.trim() || null, complemento: resposta.complemento?.trim() || null, selecionadas: resposta.selecionadas?.length ? resposta.selecionadas : null } }); }) ); return { ok: true, savedAt: new Date().toISOString() }; }