import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { revalidateTag } from "next/cache";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { generateMonumentQR } from "@/lib/qrcode";
import { getPublicUrl } from "@/lib/upload";
import {
  SUBDOMAIN_REGEX,
  SUBDOMAIN_MIN_LENGTH,
  SUBDOMAIN_MAX_LENGTH,
  TITLE_MAX_LENGTH,
  DESCRIPTION_MAX_LENGTH,
  APP_DOMAIN,
} from "@/lib/config";

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

  const hasCode = await prisma.code.findFirst({
    where: { usedByUserId: userId },
  });
  if (!hasCode) {
    return NextResponse.json({ error: "Потребен е валиден код за креирање спомен страница" }, { status: 403 });
  }

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

    if (!title?.trim() || title.length > TITLE_MAX_LENGTH) {
      return NextResponse.json({ error: `Името е задолжително (макс. ${TITLE_MAX_LENGTH} карактери)` }, { status: 400 });
    }
    if (description && description.length > DESCRIPTION_MAX_LENGTH) {
      return NextResponse.json({ error: `Описот е преголем (макс. ${DESCRIPTION_MAX_LENGTH} карактери)` }, { status: 400 });
    }
    if (!subdomain || subdomain.length < SUBDOMAIN_MIN_LENGTH || subdomain.length > SUBDOMAIN_MAX_LENGTH) {
      return NextResponse.json({ error: `Поддоменот мора да има ${SUBDOMAIN_MIN_LENGTH}-${SUBDOMAIN_MAX_LENGTH} карактери` }, { status: 400 });
    }
    if (!SUBDOMAIN_REGEX.test(subdomain)) {
      return NextResponse.json({ error: "Поддоменот може да содржи само мали букви, цифри и цртички" }, { status: 400 });
    }
    if (templateId < 1 || templateId > 3) {
      return NextResponse.json({ error: "Невалиден шаблон" }, { status: 400 });
    }
    if (!Array.isArray(images) || images.length === 0 || images.length > 3) {
      return NextResponse.json({ error: "Потребни се 1-3 фотографии" }, { status: 400 });
    }

    const existingUser = await prisma.user.findUnique({ where: { clerkId: userId } });
    if (existingUser && existingUser.subdomain !== subdomain) {
      const conflict = await prisma.user.findUnique({ where: { subdomain } });
      if (conflict && conflict.clerkId !== userId) {
        return NextResponse.json({ error: "Поддоменот е веќе зафатен" }, { status: 409 });
      }
    }

    const imageData = images.map((img: { key: string }, i: number) => ({
      url: getPublicUrl(img.key),
      key: img.key,
      order: i + 1,
    }));

    try {
      const user = await prisma.$transaction(async (tx) => {
        if (existingUser) {
          if (existingUser.subdomain !== subdomain) {
            revalidateTag(`memorial-${existingUser.subdomain}`);
          }
          await tx.image.deleteMany({ where: { userId: existingUser.id } });
          return tx.user.update({
            where: { clerkId: userId },
            data: {
              title: title.trim(),
              description: description || null,
              bornDate: bornDate || null,
              passedDate: passedDate || null,
              subdomain,
              templateId,
              published: true,
              images: { create: imageData },
            },
            include: { images: true },
          });
        }
        return tx.user.create({
          data: {
            clerkId: userId,
            title: title.trim(),
            description: description || null,
            bornDate: bornDate || null,
            passedDate: passedDate || null,
            subdomain,
            templateId,
            published: true,
            images: { create: imageData },
          },
          include: { images: true },
        });
      });

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

      const qrCode = await generateMonumentQR(subdomain);

      return NextResponse.json({
        success: true,
        monumentUrl: `https://${subdomain}.${APP_DOMAIN}`,
        qrCode,
        user,
      });
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
        return NextResponse.json({ error: "Поддоменот е веќе зафатен" }, { status: 409 });
      }
      throw error;
    }
  } catch (error) {
    console.error("Publish error:", error);
    return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
  }
}
