import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { verificarSesion } from "@/lib/auth-admin"; import { agregarFilaSheet } from "@/lib/google-sheets"; export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { const sesion = await verificarSesion("admin_session"); if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 }); const { id } = await params; const { estado, comentario } = await req.json(); // Regla: no se puede cerrar (COMPLETADO) un turno sin auto y kilometraje cargados. // Las reservas por WhatsApp los dejan vacíos; el jefe mecánico debe completarlos antes de cerrar. if (estado === "COMPLETADO") { const actual = await prisma.turno.findUnique({ where: { id }, select: { autoId: true, kilometros: true }, }); if (!actual) return NextResponse.json({ error: "Turno no encontrado" }, { status: 404 }); if (!actual.autoId || actual.kilometros == null) return NextResponse.json( { error: "Cargá el auto y el kilometraje antes de cerrar el turno" }, { status: 400 } ); } const turno = await prisma.turno.update({ where: { id }, data: { estado, ...(comentario !== undefined && { comentario }) }, include: { auto: true, tipoServicio: true, cliente: true }, }); if (estado === "COMPLETADO" && turno.auto && turno.kilometros != null) { try { await agregarFilaSheet({ patente: turno.auto.patente, kilometros: turno.kilometros, marca: turno.auto.marca, modelo: turno.auto.modelo, anio: turno.auto.anio, nombre: turno.cliente.nombre, apellido: turno.cliente.apellido, email: turno.cliente.email ?? "", telefono: turno.cliente.telefono, fecha: turno.fechaInicio, trabajo: turno.tipoServicio.nombre, comentario: turno.comentario, }); } catch (err) { console.error("Error escribiendo en Google Sheet:", err); } } return NextResponse.json(turno); }