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

export async function DELETE(req: Request, params: { params: { id: string } }) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });
  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { id } = await params.params;
    if (!id) {
      return NextResponse.json(
        { message: 'Project ID is required' },
        { status: 400 }
      );
    }

    await db.delete(project).where(eq(project.id, id)).execute();

    return NextResponse.json({ message: 'Project deleted' }, { status: 200 });
  } catch (error) {
    console.error('Error deleting project:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to delete project' },
      { status: 500 }
    );
  }
}


export async function PUT(req: Request, params: { params: { id: string } }) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });
  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { id } = await params.params;
    if (!id) {
      return NextResponse.json(
        { message: 'Project ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const doc = formData.get('doc')?.toString() ?? '';
    const link = formData.get('link')?.toString() ?? '';
    const location = formData.get('location')?.toString() ?? '';
    const complete = formData.get('complete')?.toString() ?? '';
    const slug = formData.get('slug')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const type = formData.get('type')?.toString() ?? '';
    const category = formData.get('category')?.toString() ?? '';
    const clientId = formData.get('clientId')?.toString() ?? '';
    const imageFile = formData.get('image_file') as File | null;
    const existingImage = formData.get('existing_image')?.toString() ?? null;

    // Validate required fields
    if (!title) {
      return NextResponse.json(
        { message: 'Title is required' },
        { status: 400 }
      );
    }

    const imagePath = await handleImageUpload(
      imageFile,
      existingImage
    );

    const updatedProject = await db
      .update(project)
      .set({
        title,
        description,
        doc,
        image: imagePath,
        link,
        location,
        complete,
        slug,
        status,
        type,
        category,
        clientId,
        updatedAt: new Date(),
      })
      .where(eq(project.id, id))
      .execute();

    return NextResponse.json(updatedProject[0], { status: 200 });
  } catch (error) {
    console.error('Error updating project:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to update project' },
      { status: 500 }
    );
  }
}
