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

// GET - List all span label types (active only, sorted by sort_order)
export async function GET() {
  try {
    const types = await db
      .select()
      .from(spanLabelTypes)
      .where(eq(spanLabelTypes.is_active, true))
      .orderBy(spanLabelTypes.sort_order);
    
    return NextResponse.json(types);
  } catch (error) {
    console.error('Error fetching span label types:', error);
    return NextResponse.json(
      { error: 'Failed to fetch span label types' },
      { status: 500 }
    );
  }
}

// POST - Create new span label type
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, display_name, color, hotkey, sort_order } = body;

    if (!name || !display_name || !color) {
      return NextResponse.json(
        { error: 'name, display_name, and color are required' },
        { status: 400 }
      );
    }

    const result = await db
      .insert(spanLabelTypes)
      .values({
        name,
        display_name,
        color,
        hotkey: hotkey || null,
        is_active: true,
        sort_order: sort_order ?? 0,
      })
      .returning();

    return NextResponse.json(result[0], { status: 201 });
  } catch (error: any) {
    console.error('Error creating 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 create span label type' },
      { status: 500 }
    );
  }
}
