import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { annotationTypes } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';

type RouteContext = {
  params: Promise<{ id: string }>;
};

// PATCH - Update annotation type
export async function PATCH(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const { id } = await context.params;
    const idNum = parseInt(id, 10);

    if (isNaN(idNum)) {
      return NextResponse.json(
        { error: 'Invalid parameter: id must be an integer' },
        { status: 400 }
      );
    }

    const body = await request.json();

    const { name, display_name, color, category, icon, is_active } = body;

    const updateData: any = {};
    if (name !== undefined) updateData.name = name;
    if (display_name !== undefined) updateData.display_name = display_name;
    if (color !== undefined) updateData.color = color;
    if (category !== undefined) updateData.category = category;
    if (icon !== undefined) updateData.icon = icon;
    if (is_active !== undefined) updateData.is_active = is_active;

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: 'No fields to update' },
        { status: 400 }
      );
    }

    const result = await db
      .update(annotationTypes)
      .set(updateData)
      .where(eq(annotationTypes.id, idNum))
      .returning();

    if (result.length === 0) {
      return NextResponse.json(
        { error: 'Annotation type not found' },
        { status: 404 }
      );
    }

    return NextResponse.json(result[0]);
  } catch (error: any) {
    console.error('Error updating annotation type:', error);

    if (error.message?.includes('UNIQUE constraint failed')) {
      return NextResponse.json(
        { error: 'Annotation type with this name already exists' },
        { status: 409 }
      );
    }

    return NextResponse.json(
      { error: 'Failed to update annotation type' },
      { status: 500 }
    );
  }
}
