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

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    const body = await req.json();
    if (!body.title || !body.title.trim()) return fail("Title is required");

    const data: any = {
      title: body.title,
      excerpt: body.excerpt || "",
      content: body.content || "",
      category: body.category || null,
      tags: JSON.stringify(body.tags || []),
      featuredImage: body.featuredImage || null,
      isPublished: body.isPublished ?? false,
      authorName: body.authorName || null,
      metaTitle: body.metaTitle || null,
      metaDescription: body.metaDescription || null,
    };

    if (body.slug) {
      const slug = slugify(body.slug);
      if (!slug) return fail("A valid slug is required");
      const existing = await db.blogPost.findUnique({ where: { slug } });
      if (existing && existing.id !== id) return fail("A blog post with this slug already exists");
      data.slug = slug;
    }

    // Handle publishedAt logic
    const isPublished = body.isPublished ?? false;
    const current = await db.blogPost.findUnique({ where: { id } });
    if (isPublished) {
      if (body.publishedAt) {
        const d = new Date(body.publishedAt);
        data.publishedAt = isNaN(d.getTime()) ? new Date() : d;
      } else if (!current?.publishedAt) {
        data.publishedAt = new Date();
      } else {
        data.publishedAt = current.publishedAt;
      }
    } else {
      data.publishedAt = null;
    }

    const post = await db.blogPost.update({ where: { id }, data });
    return ok({ post });
  } catch (e) {
    console.error(e);
    return fail("Failed to update blog post", 500);
  }
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    await db.blogPost.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    return fail("Failed to delete blog post", 500);
  }
}
