import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail, slugify } from "@/lib/admin-api";

export async function POST(req: NextRequest) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const body = await req.json();
    if (!body.title || !body.title.trim()) return fail("Title is required");
    if (!body.excerpt || !body.excerpt.trim()) return fail("Excerpt is required");
    if (!body.content || !body.content.trim()) return fail("Content is required");

    const slug = body.slug ? slugify(body.slug) : slugify(body.title);
    if (!slug) return fail("A valid title or slug is required");

    const existing = await db.blogPost.findUnique({ where: { slug } });
    if (existing) return fail("A blog post with this slug already exists");

    const isPublished = body.isPublished ?? false;
    let publishedAt: Date | null = null;
    if (isPublished) {
      if (body.publishedAt) {
        const d = new Date(body.publishedAt);
        publishedAt = isNaN(d.getTime()) ? new Date() : d;
      } else {
        publishedAt = new Date();
      }
    }

    const post = await db.blogPost.create({
      data: {
        title: body.title,
        slug,
        excerpt: body.excerpt,
        content: body.content,
        category: body.category || null,
        tags: JSON.stringify(body.tags || []),
        featuredImage: body.featuredImage || null,
        isPublished,
        publishedAt,
        authorName: body.authorName || null,
        metaTitle: body.metaTitle || null,
        metaDescription: body.metaDescription || null,
      },
    });
    return ok({ post });
  } catch (e) {
    console.error(e);
    return fail("Failed to create blog post", 500);
  }
}
