import { eq } from 'drizzle-orm';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { photo } from '@/db/schema';
import { handleImageUpload } from '@/lib/image-upload';

export async function GET(req: Request) {
  try {
    const images = await db.select().from(photo);

    return NextResponse.json(images);
  } catch (error) {
    console.error('Error fetching images:', error);
    return NextResponse.json(
      { message: 'Failed to fetch images' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const description = formData.get('description') as string;
    const type = formData.get('type') as string;
    const images = formData.getAll('images') as File[];

    if (!description || images.length === 0) {
      return NextResponse.json(
        { message: 'Project ID and at least one image are required' },
        { status: 400 }
      );
    }

    const uploadedImageUrls = await Promise.all(
      images.map((image) => handleImageUpload(image, null))
    );

    const newImages = uploadedImageUrls.map((url) => ({
      id: crypto.randomUUID(),
      type,
      description,
      url,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    await db.insert(photo).values(newImages);

    return NextResponse.json({ success: true }, { status: 201 });
  } catch (error) {
    console.error('Error uploading images:', error);
    return NextResponse.json(
      { message: 'Failed to upload images' },
      { status: 500 }
    );
  }
}
