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) {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  try {
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
      include: { images: true },
    });

    if (!user) {
      return NextResponse.json({ error: "Споменот не е пронајден" }, { status: 404 });
    }

    await Promise.all(
      user.images.map((image) =>
        deleteS3Object(image.key).catch((e) =>
          console.error("Не успеа бришењето на S3 објект:", image.key, e)
        )
      )
    );

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

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

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

export async function GET() {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  const user = await prisma.user.findUnique({
    where: { clerkId: userId },
    include: { images: { orderBy: { order: "asc" } } },
  });

  if (!user) {
    return NextResponse.json({ error: "Споменот не е пронајден" }, { status: 404 });
  }

  return NextResponse.json({ user });
}

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

  try {
    const body = await req.json();
    const { title, description, bornDate, passedDate, templateId, published } = body;

    const existingUser = await prisma.user.findUnique({ where: { clerkId: userId } });
    const oldSubdomain = existingUser?.subdomain;

    const user = await prisma.user.update({
      where: { clerkId: userId },
      data: {
        ...(title !== undefined && { title }),
        ...(description !== undefined && { description }),
        ...(bornDate !== undefined && { bornDate }),
        ...(passedDate !== undefined && { passedDate }),
        ...(templateId !== undefined && { templateId }),
        ...(published !== undefined && { published }),
      },
      include: { images: { orderBy: { order: "asc" } } },
    });

    revalidateTag("memorial");
    revalidateTag(`memorial-${user.subdomain}`);
    if (oldSubdomain && oldSubdomain !== user.subdomain) {
      revalidateTag(`memorial-${oldSubdomain}`);
    }

    return NextResponse.json({ user });
  } catch (error) {
    console.error("Update error:", error);
    return NextResponse.json({ error: "Не успеа ажурирањето на споменот" }, { status: 500 });
  }
}