import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { team } 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: 'Team ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const name = formData.get('name')?.toString() ?? '';
    const facebook = formData.get('facebook')?.toString() ?? '';
    const twitter = formData.get('twitter')?.toString() ?? '';
    const linkedin = formData.get('linkedin')?.toString() ?? '';
    const title = formData.get('title')?.toString() ?? '';
    const email = formData.get('email')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const about = formData.get('about')?.toString() ?? '';
    const role = formData.get('role')?.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 updatedTeam = await db
      .update(team)
      .set({
        name,
        facebook,
        twitter,
        linkedin,
        title,
        image: imagePath,
        email,
        status,
        about,
        role,
        updatedAt: new Date(),
      })
      .where(eq(team.id, id))
      .execute();

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