import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { isValidObjectId } from "mongoose"; import { connectDb } from "@/lib/server/db"; import { Branch } from "@/lib/server/models/Branch"; import { authorize } from "@/lib/server/auth"; export const runtime = "nodejs"; const updateSchema = z .object({ branchName: z.string().trim().min(1).max(120).optional(), locationCity: z.string().trim().min(1).max(120).optional(), }) .refine((v) => Object.keys(v).length > 0, { message: "No fields to update" }); // PATCH /api/branches/:id — owner renames a branch or changes its city. export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) { await connectDb(); const gate = authorize(req, ["SUPER_ADMIN"]); if (!gate.ok) return gate.response; const auth = gate.auth; if (!isValidObjectId(params.id)) return NextResponse.json({ error: "Branch not found" }, { status: 404 }); const json = await req.json().catch(() => null); const parsed = updateSchema.safeParse(json); if (!parsed.success) { return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 }); } const branch = await Branch.findOneAndUpdate({ _id: params.id, businessId: auth.businessId }, parsed.data, { new: true, }).lean(); if (!branch) return NextResponse.json({ error: "Branch not found" }, { status: 404 }); return NextResponse.json({ branch }); }