import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const establishmentId = searchParams.get("establishmentId");

  const templates = await prisma.template.findMany({
    where: {
      OR: [
        { isPublic: true },
        ...(establishmentId ? [{ establishmentId }] : []),
      ],
    },
    orderBy: { createdAt: "desc" },
  });
  return NextResponse.json(templates);
}

export async function POST(req: NextRequest) {
  const body = await req.json();
  const { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
  const template = await prisma.template.create({
    data: { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy },
  });
  return NextResponse.json(template, { status: 201 });
}

export async function PUT(req: NextRequest) {
  const body = await req.json();
  const { id, ...data } = body;
  const template = await prisma.template.update({ where: { id }, data });
  return NextResponse.json(template);
}

export async function DELETE(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
  await prisma.template.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}
