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

export async function GET(req: Request) {
  await dbConnect();
  const { searchParams } = new URL(req.url);
  const category = searchParams.get('category'); // 'news' or 'blog'
  
  try {
    const filter = category ? { categories: category } : {};
    const posts = await (Post as any).find(filter).sort({ createdAt: -1 });
    return NextResponse.json(posts);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch posts' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  await dbConnect();
  try {
    const body = await req.json();
    
    // Generate slug
    let slug = slugify(body.title, { lower: true, strict: true });
    
    // Ensure slug uniqueness
    const exists = await (Post as any).findOne({ slug });
    if (exists) {
      slug = `${slug}-${Date.now()}`;
    }

    const post = await (Post as any).create({
      ...body,
      slug,
      status: 'published',
      publishedAt: new Date()
    });
    
    return NextResponse.json(post);
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Failed to create post' }, { status: 500 });
  }
}