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) {
  const authUser = await getAuthUserFromRequest(request);
  if (!authUser) {
    return NextResponse.json({ message: "프로젝트 목록을 조회하려면 로그인이 필요합니다." }, { status: 401 });
  }

  try {
    const projects = await prisma.project.findMany({
      where: { userId: authUser.id },
      orderBy: { createdAt: "desc" },
      take: 50,
      select: {
        id: true,
        title: true,
        slug: true,
        status: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    return NextResponse.json(projects, { status: 200 });
  } catch (error: any) {
    return NextResponse.json(
      { message: "프로젝트 목록을 가져오는 중 오류가 발생했습니다.", error: error?.message },
      { status: 500 },
    );
  }
}

export async function POST(request: Request) {
  const authUser = await getAuthUserFromRequest(request);
  if (!authUser) {
    return NextResponse.json({ message: "프로젝트를 저장하려면 로그인이 필요합니다." }, { status: 401 });
  }

  const body = await request.json();
  const { title, slug, contentJson } = body;

  if (!title || !slug || typeof title !== "string" || typeof slug !== "string") {
    return NextResponse.json({ message: "title과 slug는 필수입니다." }, { status: 400 });
  }

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

    if (existing && existing.userId && existing.userId !== authUser.id) {
      return NextResponse.json(
        { message: "이미 다른 사용자가 사용 중인 프로젝트 주소입니다." },
        { status: 409 },
      );
    }

    const project = await prisma.project.upsert({
      where: { slug },
      update: {
        title,
        contentJson,
      },
      create: {
        title,
        slug,
        contentJson,
        userId: authUser.id,
      },
    });

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