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

export async function PUT(req: Request, props: { params: Promise<{ id: string }> }) {
  const params = await props.params;
  await dbConnect();
  try {
    const body = await req.json();
    const images = Array.isArray(body.images) ? body.images.filter(Boolean) : [];
    const imageUrl = body.imageUrl || images[0];
    const name = body.name || body.title || 'Untitled';

    if (!imageUrl) {
      return NextResponse.json({ error: 'At least one image is required' }, { status: 400 });
    }

    const item = await (GalleryItem as any).findByIdAndUpdate(
      params.id,
      {
        $set: {
          name,
          title: name,
          images: images.length > 0 ? images : [imageUrl],
          imageUrl,
          status: body.status || 'published'
        }
      },
      { new: true }
    );

    if (!item) return NextResponse.json({ error: 'Item not found' }, { status: 404 });
    return NextResponse.json(item);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to update item' }, { status: 500 });
  }
}

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