import { z } from "zod";
import prisma from "@/server/db/prisma";
import { HttpError } from "@/server/http/errors";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { DeleteByIdSchema } from "@/server/http/schemas";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { deleteEntityImage } from "@/server/uploads/cleanup";

// GET: Fetch all bold products
export const GET = withErrorHandling(async () => {
  const products = await prisma.bold.findMany({ orderBy: { id: "desc" } });
  return ok(products);
});

// POST: Add or update a bold product
const BoldUpsertSchema = z.object({
  id: z.coerce.number().int().optional(),
  name: z.string().min(1),
  description: z.string().min(1),
  link: z.string().min(1),
  image: z.string().optional().default(""),
});

export const POST = withErrorHandling(async (request: Request) => {
  const formData = await request.formData();
  const parsed = BoldUpsertSchema.parse({
    id: formData.get("id") ?? undefined,
    name: formData.get("name"),
    description: formData.get("description"),
    link: formData.get("link"),
    image: formData.get("image") ?? "",
  });

  if (parsed.id) {
    const updatedProduct = await prisma.bold.update({
      where: { id: parsed.id },
      data: {
        name: parsed.name,
        description: parsed.description,
        link: parsed.link,
        image: parsed.image || "",
      },
    });
    return ok(updatedProduct);
  }

  const newProduct = await prisma.bold.create({
    data: {
      name: parsed.name,
      description: parsed.description,
      link: parsed.link,
      image: parsed.image || "",
    },
  });
  return ok(newProduct);
});

// DELETE: Delete a bold product
export const DELETE = withErrorHandling(async (request: Request) => {
  const { id } = await parseJson(request, DeleteByIdSchema);

  const product = await prisma.bold.findUnique({ where: { id } });
  if (!product) throw new HttpError("Bold product not found", { status: 404 });

  await prisma.bold.delete({ where: { id } });

  // Delete image (non-blocking, errors are silently ignored)
  await deleteEntityImage(product.image);

  return ok({ success: true });
});
