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

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const projectId = searchParams.get('projectId');

    let moreProjectsData;
    if (projectId) {
      moreProjectsData = await db.select().from(moreProject).where(eq(moreProject.projectId, projectId));
    } else {
      moreProjectsData = await db.select().from(moreProject);
    }
    return NextResponse.json(moreProjectsData);
  } catch (error) {
    console.error('Error fetching more projects:', error);
    return NextResponse.json(
      { message: 'Failed to fetch more projects' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const formData = await req.formData();

    const projectId = formData.get('projectId')?.toString() ?? '';
    const doc = formData.get('doc')?.toString() ?? '';
    const position = formData.get('position')?.toString() ?? 'right';
    const imageFile = formData.get('image_file') as File | null;

    const imagePath = await handleImageUpload(imageFile, null);

    const newMoreProject = await db.insert(moreProject).values({
      id: crypto.randomUUID(),
      projectId,
      doc,
      image: imagePath,
      position: position as 'left' | 'right',
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    return NextResponse.json(newMoreProject, { status: 201 });
  } catch (error: any) {
    console.error('Error creating more project:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to create more project' },
      { status: 500 }
    );
  }
}
