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

// GET - List all span annotations for a chart
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    const chartId = searchParams.get('chartId');

    if (!chartId) {
      return NextResponse.json(
        { error: 'chartId parameter is required' },
        { status: 400 }
      );
    }

    const chartIdNum = parseInt(chartId, 10);
    if (isNaN(chartIdNum)) {
      return NextResponse.json(
        { error: 'Invalid parameter: chartId must be an integer' },
        { status: 400 }
      );
    }

    const spans = await db
      .select()
      .from(spanAnnotations)
      .where(eq(spanAnnotations.chart_id, chartIdNum))
      .orderBy(desc(spanAnnotations.start_time));

    const normalized = spans.map((s) => ({
      ...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,
    }));

    return NextResponse.json(normalized);
  } catch (error) {
    console.error('Error fetching span annotations:', error);
    return NextResponse.json(
      { error: 'Failed to fetch span annotations' },
      { status: 500 }
    );
  }
}

// POST - Create new span annotation
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      chart_id,
      start_time,
      end_time,
      label,
      confidence,
      outcome,
      notes,
      sub_spans,
      color,
      source,
      model_prediction,
    } = body;

    if (!chart_id || start_time === undefined || end_time === undefined || !label) {
      return NextResponse.json(
        { error: 'chart_id, start_time, end_time, and label are required' },
        { status: 400 }
      );
    }

    // Ensure start_time <= end_time (swap if needed)
    const actualStartTime = Math.min(start_time, end_time);
    const actualEndTime = Math.max(start_time, end_time);

    const result = await db
      .insert(spanAnnotations)
      .values({
        chart_id,
        start_time: new Date(actualStartTime * 1000),
        end_time: new Date(actualEndTime * 1000),
        label,
        confidence: confidence || null,
        outcome: outcome || null,
        notes: notes || null,
        sub_spans: sub_spans || null,
        color: color || '#2196F3',
        source: source || 'human', // 'human', 'model', or 'human_correction'
        model_prediction: model_prediction || null,
      })
      .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,
    }, { status: 201 });
  } catch (error: any) {
    console.error('Error creating span annotation:', error);
    return NextResponse.json(
      { error: 'Failed to create span annotation' },
      { status: 500 }
    );
  }
}

// DELETE - Bulk delete span annotations by chartId + optional source/label filters
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    const chartId = searchParams.get('chartId');
    const source = searchParams.get('source');
    const label = searchParams.get('label');

    if (!chartId) {
      return NextResponse.json(
        { error: 'chartId parameter is required' },
        { status: 400 }
      );
    }

    const chartIdInt = parseInt(chartId, 10);
    if (isNaN(chartIdInt)) {
      return NextResponse.json(
        { error: 'Invalid parameter: chartId must be an integer' },
        { status: 400 }
      );
    }

    // Build filter conditions
    const conditions = [eq(spanAnnotations.chart_id, chartIdInt)];
    if (source) conditions.push(eq(spanAnnotations.source, source));
    if (label) conditions.push(eq(spanAnnotations.label, label));

    const deleted = await db
      .delete(spanAnnotations)
      .where(and(...conditions))
      .returning({ id: spanAnnotations.id });

    return NextResponse.json({ deleted: deleted.length });
  } catch (error) {
    console.error('Error bulk deleting span annotations:', error);
    return NextResponse.json(
      { error: 'Failed to delete span annotations' },
      { status: 500 }
    );
  }
}
