import { requireAdminApi } from "@/lib/admin-api";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function GET() {
  const deny = await requireAdminApi();
  if (deny) return deny;

  const items = await prisma.galleryImage.findMany({
    orderBy: { sortOrder: "asc" },
  });
  return NextResponse.json(items);
}

export async function POST(req: Request) {
  const deny = await requireAdminApi();
  if (deny) return deny;

  try {
    const body = await req.json();
    const url = String(body.url ?? "").trim();
    if (!url) {
      return NextResponse.json({ error: "url required" }, { status: 400 });
    }

    const max = await prisma.galleryImage.aggregate({ _max: { sortOrder: true } });
    const sortOrder = (max._max.sortOrder ?? -1) + 1;

    const row = await prisma.galleryImage.create({
      data: {
        url,
        altEn: String(body.altEn ?? ""),
        altAr: String(body.altAr ?? ""),
        altRu: String(body.altRu ?? ""),
        altIt: String(body.altIt ?? ""),
        sortOrder,
      },
    });
    return NextResponse.json(row);
  } catch {
    return NextResponse.json({ error: "Bad request" }, { status: 400 });
  }
}

export async function PATCH(req: Request) {
  const deny = await requireAdminApi();
  if (deny) return deny;

  try {
    const body = await req.json();
    const id = String(body.id ?? "");
    if (!id) {
      return NextResponse.json({ error: "id required" }, { status: 400 });
    }

    const data: Record<string, string | number> = {};
    if (typeof body.url === "string") data.url = body.url;
    if (typeof body.altEn === "string") data.altEn = body.altEn;
    if (typeof body.altAr === "string") data.altAr = body.altAr;
    if (typeof body.altRu === "string") data.altRu = body.altRu;
    if (typeof body.altIt === "string") data.altIt = body.altIt;
    if (typeof body.sortOrder === "number") data.sortOrder = body.sortOrder;

    const row = await prisma.galleryImage.update({
      where: { id },
      data,
    });
    return NextResponse.json(row);
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
}

export async function DELETE(req: Request) {
  const deny = await requireAdminApi();
  if (deny) return deny;

  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  if (!id) {
    return NextResponse.json({ error: "id required" }, { status: 400 });
  }

  try {
    await prisma.galleryImage.delete({ where: { id } });
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
}
