import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
import { verifyAccessToken } from "@/features/auth/authCrypto";

const prisma = new PrismaClient();

interface AuthUser {
  id: string;
  email: string;
  tokenVersion: number;
}

function extractTokenFromCookieHeader(cookieHeader: string | null): string | null {
  if (!cookieHeader) return null;

  const parts = cookieHeader.split(";");
  for (const part of parts) {
    const trimmed = part.trim();
    if (trimmed.startsWith("pb_access=")) {
      const value = trimmed.substring("pb_access=".length);
      return decodeURIComponent(value);
    }
  }
  return null;
}

async function getAuthUserFromRequest(request: Request): Promise<AuthUser | null> {
  const cookieHeader = request.headers.get("cookie");
  const token = extractTokenFromCookieHeader(cookieHeader);
  if (!token) return null;

  const payload = await verifyAccessToken(token);
  if (!payload) return null;

  return {
    id: payload.sub,
    email: payload.email,
    tokenVersion: payload.tokenVersion,
  };
}

export async function GET(
  request: Request,
  context: { params: { slug: string } | Promise<{ slug: string }> },
) {
  const authUser = await getAuthUserFromRequest(request);
  if (!authUser) {
    return NextResponse.json({ message: "프로젝트를 조회하려면 로그인이 필요합니다." }, { status: 401 });
  }

  const { slug } = await context.params;

  const project = await prisma.project.findUnique({
    where: { slug },
  });

  if (!project || (project.userId && project.userId !== authUser.id)) {
    return NextResponse.json({ message: "프로젝트를 찾을 수 없습니다." }, { status: 404 });
  }

  return NextResponse.json(project, { status: 200 });
}

export async function DELETE(
  request: Request,
  context: { params: { slug: string } | Promise<{ slug: string }> },
) {
  const authUser = await getAuthUserFromRequest(request);
  if (!authUser) {
    return NextResponse.json({ message: "프로젝트를 삭제하려면 로그인이 필요합니다." }, { status: 401 });
  }

  const { slug } = await context.params;

  try {
    const project = await prisma.project.findUnique({
      where: { slug },
    });

    if (!project || (project.userId && project.userId !== authUser.id)) {
      return NextResponse.json({ message: "프로젝트를 찾을 수 없습니다." }, { status: 404 });
    }

    await prisma.project.delete({
      where: { slug },
    });

    return NextResponse.json({ message: "프로젝트가 삭제되었습니다." }, { status: 200 });
  } catch (error: any) {
    // Prisma NotFound 에러 코드(P2025)가 떨어지는 경우 404 로 매핑한다.
    if (error?.code === "P2025") {
      return NextResponse.json({ message: "프로젝트를 찾을 수 없습니다." }, { status: 404 });
    }

    return NextResponse.json(
      { message: "프로젝트 삭제 중 오류가 발생했습니다.", error: error?.message },
      { status: 500 },
    );
  }
}
