import { NextResponse } from "next/server";

import { verifyAccessToken } from "@/features/auth/authCrypto";

// /api/auth/me
// - 요청 쿠키에 포함된 JWT(pb_access)를 검증하고,
// - 유효한 경우 토큰에서 식별 가능한 유저 정보를 반환한다.

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;
}

export async function GET(request: Request) {
  const cookieHeader = request.headers.get("cookie");
  const token = extractTokenFromCookieHeader(cookieHeader);

  if (!token) {
    return NextResponse.json({ message: "인증 정보가 없습니다." }, { status: 401 });
  }

  const payload = await verifyAccessToken(token);

  if (!payload) {
    return NextResponse.json({ message: "유효하지 않은 토큰입니다." }, { status: 401 });
  }

  const user = {
    id: payload.sub,
    email: payload.email,
    tokenVersion: payload.tokenVersion,
  };

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