import { getSessionUser } from "@/lib/auth";
import {
  getKavenixGoogleSearchConsoleBlogStatus,
  inspectGoogleSearchConsoleBlogPosts,
} from "@/lib/google-search-console";
import { isKavenixAdminEmail } from "@/lib/kavenix-admin";
import { getMarketingBlogPostById } from "@/lib/marketing-blog";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const user = await getSessionUser();

  if (!user || !isKavenixAdminEmail(user.email)) {
    return Response.json({ error: "forbidden" }, { status: 403 });
  }

  try {
    const body = (await request.json().catch(() => ({}))) as { postId?: unknown };
    const postId = Number(body.postId);

    if (!Number.isInteger(postId) || postId <= 0) {
      return Response.json(
        { error: "invalid-post-id", message: "확인할 게시글을 찾지 못했습니다." },
        { status: 400 },
      );
    }

    const post = await getMarketingBlogPostById(postId);

    if (!post) {
      return Response.json(
        { error: "blog-post-not-found", message: "게시글을 찾지 못했습니다." },
        { status: 404 },
      );
    }

    const result = await inspectGoogleSearchConsoleBlogPosts({ force: true, postId });

    if (result.status === "not-published") {
      return Response.json(
        { error: "blog-post-not-published", message: "발행된 게시글만 색인 상태를 확인할 수 있습니다." },
        { status: 400 },
      );
    }

    const status = await getKavenixGoogleSearchConsoleBlogStatus([post]);

    return Response.json({
      ok: true,
      result,
      status: status.posts[0] ?? null,
    });
  } catch (error) {
    return Response.json(
      {
        error: "google-search-console-blog-inspection-failed",
        message: error instanceof Error ? error.message : "게시글 색인 상태 확인에 실패했습니다.",
      },
      { status: 500 },
    );
  }
}
