import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail } from "@/lib/admin-api";

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    const body = await req.json();
    if (!body.title || !body.title.trim()) return fail("Title is required");
    if (!body.beforeImage) return fail("Before image is required");
    if (!body.afterImage) return fail("After image is required");

    const item = await db.beforeAfter.update({
      where: { id },
      data: {
        title: body.title,
        description: body.description || null,
        category: body.category || null,
        location: body.location || null,
        completionDate: body.completionDate || null,
        beforeImage: body.beforeImage,
        afterImage: body.afterImage,
        isEnabled: body.isEnabled ?? true,
        order: body.order ?? 0,
      },
    });
    return ok({ item });
  } catch (e) {
    console.error(e);
    return fail("Failed to update before/after entry", 500);
  }
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    await db.beforeAfter.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    return fail("Failed to delete before/after entry", 500);
  }
}
