import { NextResponse } from 'next/server';
import dbConnect from '@/lib/db';
import Event from '@/models/Event';
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 title changed, regenerate slug (optional, but good practice)
    if (body.title) {
       const oldEvent = await (Event as any).findById(params.id);
       if (oldEvent && oldEvent.title !== body.title) {
         let slug = slugify(body.title, { lower: true, strict: true });
         const exists = await (Event as any).findOne({ slug, _id: { $ne: params.id } });
         if (exists) slug = `${slug}-${Date.now()}`;
         body.slug = slug;
       }
    }

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

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