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

export async function GET() {
  await dbConnect();
  try {
    const events = await (Event as any).find({}).sort({ startDate: -1 });
    return NextResponse.json(events);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch events' }, { 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 (simple logic)
    const exists = await (Event as any).findOne({ slug });
    if (exists) {
      slug = `${slug}-${Date.now()}`;
    }

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