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

// PATCH - Update span annotation
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 { label, confidence, outcome, notes, sub_spans } = body;

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

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

    // Build update object with only provided fields
    const updates: any = {};
    if (label !== undefined) updates.label = label;
    if (confidence !== undefined) updates.confidence = confidence;
    if (outcome !== undefined) updates.outcome = outcome;
    if (notes !== undefined) updates.notes = notes;
    if (sub_spans !== undefined) updates.sub_spans = sub_spans || null;

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

    const s = result[0];
    return NextResponse.json({
      ...s,
      start_time: s.start_time instanceof Date ? Math.floor(s.start_time.getTime() / 1000) : s.start_time,
      end_time: s.end_time instanceof Date ? Math.floor(s.end_time.getTime() / 1000) : s.end_time,
      created_at: s.created_at instanceof Date ? Math.floor(s.created_at.getTime() / 1000) : s.created_at,
    });
  } catch (error: any) {
    console.error('Error updating span annotation:', error);
    return NextResponse.json(
      { error: 'Failed to update span annotation' },
      { status: 500 }
    );
  }
}

// DELETE - Delete span annotation
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 span exists
    const existing = await db
      .select()
      .from(spanAnnotations)
      .where(eq(spanAnnotations.id, idNum))
      .limit(1);

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

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

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