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



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: 'Client ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const name = formData.get('name')?.toString() ?? '';
    const position = formData.get('position')?.toString() ?? '';
    const company = formData.get('company')?.toString() ?? '';
    const link = formData.get('link')?.toString() ?? '';
    const content = formData.get('content')?.toString() ?? '';
    const imageFile = formData.get('image_file') as File | null;
    const existingImage = formData.get('existing_image')?.toString() ?? null;

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

    const imagePath = await handleImageUpload(
      imageFile,
      existingImage
    );

    const updatedClient = await db
      .update(client)
      .set({
        name,
        position,
        company,
        link,
        content,
        image: imagePath,
        updatedAt: new Date(),
      })
      .where(eq(client.id, id))
      .execute();

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