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

export async function GET() {
  await dbConnect();
  try {
    const items = await (GalleryItem as any).find({}).sort({ order: 1 });
    return NextResponse.json(items);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch gallery' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  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 count = await (GalleryItem as any).countDocuments();
    const newItem = await (GalleryItem as any).create({
      ...body,
      name,
      title: name,
      images: images.length > 0 ? images : [imageUrl],
      imageUrl,
      order: count, // Append to end
    });
    return NextResponse.json(newItem);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to create item' }, { status: 500 });
  }
}
