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

// PATCH - Update span label type
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await 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, hotkey, is_active, sort_order } = body;

    // Check if the type exists
    const existing = await db
      .select()
      .from(spanLabelTypes)
      .where(eq(spanLabelTypes.id, idNum))
      .limit(1);

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

    // Build update object with only provided fields
    const updates: any = {};
    if (name !== undefined) updates.name = name;
    if (display_name !== undefined) updates.display_name = display_name;
    if (color !== undefined) updates.color = color;
    if (hotkey !== undefined) updates.hotkey = hotkey;
    if (is_active !== undefined) updates.is_active = is_active;
    if (sort_order !== undefined) updates.sort_order = sort_order;

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

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

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

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

// DELETE - Delete span label type (only if no span annotations use it)
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const idNum = parseInt(id, 10);

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

    // Check if the type exists
    const type = await db
      .select()
      .from(spanLabelTypes)
      .where(eq(spanLabelTypes.id, idNum))
      .limit(1);

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

    // Check if any span annotations use this label
    const existingSpans = await db
      .select()
      .from(spanAnnotations)
      .where(eq(spanAnnotations.label, type[0].name))
      .limit(1);

    if (existingSpans.length > 0) {
      return NextResponse.json(
        { error: 'Cannot delete span label type: span annotations exist with this label' },
        { status: 409 }
      );
    }

    await db.delete(spanLabelTypes).where(eq(spanLabelTypes.id, idNum));

    return NextResponse.json({ message: 'Span label type deleted successfully' });
  } catch (error) {
    console.error('Error deleting span label type:', error);
    return NextResponse.json(
      { error: 'Failed to delete span label type' },
      { status: 500 }
    );
  }
}
