import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { revalidateTag } from "next/cache";
import { prisma } from "@/lib/prisma";
import { deleteS3Object } from "@/lib/s3";

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ imageId: string }> }
) {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  const { imageId } = await params;

  try {
    const image = await prisma.image.findUnique({
      where: { id: imageId },
      include: { user: true },
    });

    if (!image || image.user.clerkId !== userId) {
      return NextResponse.json({ error: "Фотографијата не е пронајдена" }, { status: 404 });
    }

    try {
      await deleteS3Object(image.key);
    } catch (e) {
      console.error("Не успеа бришењето на S3 објект:", image.key, e);
    }

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

    const remainingImages = await prisma.image.findMany({
      where: { userId: image.userId },
      orderBy: { order: "asc" },
    });

    await prisma.$transaction(
      remainingImages.map((img, i) =>
        prisma.image.update({
          where: { id: img.id },
          data: { order: i + 1 },
        })
      )
    );

    revalidateTag("memorial");
    revalidateTag(`memorial-${image.user.subdomain}`);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Delete image error:", error);
    return NextResponse.json({ error: "Не успеа бришењето на фотографијата" }, { status: 500 });
  }
}