import { revalidatePath } from "next/cache";
import { getSessionUser } from "@/lib/auth";
import {
  deleteMarketingBlogPost,
  updateMarketingBlogPost,
  type MarketingBlogPostInput,
} from "@/lib/marketing-blog";
import { isKavenixAdminEmail } from "@/lib/kavenix-admin";

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

type RouteContext = {
  params: Promise<{ postId: string }>;
};

function errorMessage(error: unknown) {
  const code = error instanceof Error ? error.message : "blog-post-save-failed";

  if (code === "blog-post-not-found") {
    return "블로그 글을 찾을 수 없습니다.";
  }

  if (code === "invalid-blog-slug") {
    return "URL 슬러그는 영문 소문자, 숫자, 하이픈(-)만 사용해 3자 이상 입력해 주세요.";
  }

  if (code.startsWith("invalid-blog-")) {
    return "제목, 요약, SEO 설명, 본문 입력값을 다시 확인해 주세요.";
  }

  if (code.includes("ER_DUP_ENTRY")) {
    return "이미 사용 중인 URL 슬러그입니다.";
  }

  return "블로그 글 저장 중 오류가 발생했습니다.";
}

async function requireAdmin() {
  const user = await getSessionUser();

  if (!user || !isKavenixAdminEmail(user.email)) {
    return null;
  }

  return user;
}

async function readPostId(context: RouteContext) {
  const { postId } = await context.params;
  const id = Number(postId);
  return Number.isInteger(id) && id > 0 ? id : null;
}

export async function PATCH(request: Request, context: RouteContext) {
  if (!(await requireAdmin())) {
    return Response.json({ error: "forbidden", message: "최고관리자만 블로그 글을 수정할 수 있습니다." }, { status: 403 });
  }

  const id = await readPostId(context);
  const payload = await request.json().catch(() => null) as MarketingBlogPostInput | null;

  if (!id || !payload) {
    return Response.json({ error: "invalid-request", message: "작성 내용을 다시 확인해 주세요." }, { status: 400 });
  }

  try {
    const post = await updateMarketingBlogPost(id, payload);

    if (!post) {
      throw new Error("blog-post-not-found");
    }

    revalidatePath("/blog");
    revalidatePath(`/blog/${post.slug}`);
    revalidatePath("/sitemap.xml");

    return Response.json({ ok: true, post, message: post.status === "published" ? "블로그 글을 발행 상태로 저장했습니다." : "임시저장했습니다." });
  } catch (error) {
    return Response.json(
      { error: "blog-post-save-failed", message: errorMessage(error) },
      { status: 400 },
    );
  }
}

export async function DELETE(_: Request, context: RouteContext) {
  if (!(await requireAdmin())) {
    return Response.json({ error: "forbidden", message: "최고관리자만 블로그 글을 삭제할 수 있습니다." }, { status: 403 });
  }

  const id = await readPostId(context);

  if (!id) {
    return Response.json({ error: "invalid-request", message: "블로그 글 정보를 다시 확인해 주세요." }, { status: 400 });
  }

  try {
    await deleteMarketingBlogPost(id);
    revalidatePath("/blog");
    revalidatePath("/sitemap.xml");
    return Response.json({ ok: true, message: "블로그 글을 삭제했습니다." });
  } catch (error) {
    return Response.json(
      { error: "blog-post-delete-failed", message: errorMessage(error) },
      { status: 400 },
    );
  }
}
