import { NextResponse } from 'next/server';
import dbConnect from '@/lib/db';
import Post from '@/models/Post';
import slugify from 'slugify';

export async function PUT(req: Request, props: { params: Promise<{ id: string }> }) {
  const params = await props.params;
  await dbConnect();
  try {
    const body = await req.json();

    if (body.title) {
       const oldPost = await (Post as any).findById(params.id);
       if (oldPost && oldPost.title !== body.title) {
         let slug = slugify(body.title, { lower: true, strict: true });
         const exists = await (Post as any).findOne({ slug, _id: { $ne: params.id } });
         if (exists) slug = `${slug}-${Date.now()}`;
         body.slug = slug;
       }
    }

    const post = await (Post as any).findByIdAndUpdate(params.id, body, { new: true });
    if (!post) return NextResponse.json({ error: 'Post not found' }, { status: 404 });
    return NextResponse.json(post);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to update post' }, { status: 500 });
  }
}

export async function DELETE(req: Request, props: { params: Promise<{ id: string }> }) {
  const params = await props.params;
  await dbConnect();
  try {
    const post = await (Post as any).findByIdAndDelete(params.id);
    if (!post) return NextResponse.json({ error: 'Post not found' }, { status: 404 });
    return NextResponse.json({ message: 'Post deleted' });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to delete post' }, { status: 500 });
  }
}