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

// GET - List all annotation types
export async function GET() {
  try {
    const types = await db.select().from(annotationTypes);
    return NextResponse.json(types);
  } catch (error) {
    console.error('Error fetching annotation types:', error);
    return NextResponse.json(
      { error: 'Failed to fetch annotation types' },
      { status: 500 }
    );
  }
}

// POST - Create new annotation type or seed defaults
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Special case: seed default types
    if (body.action === 'seed') {
      const existing = await db.select().from(annotationTypes);
      
      if (existing.length > 0) {
        return NextResponse.json({ message: 'Types already seeded' });
      }

      const defaultTypes = [
        {
          name: 'break_up',
          display_name: 'Break Up',
          color: '#10b981',
          category: 'marker',
          icon: 'arrowUp',
          is_active: true,
        },
        {
          name: 'break_down',
          display_name: 'Break Down',
          color: '#ef4444',
          category: 'marker',
          icon: 'arrowDown',
          is_active: true,
        },
        {
          name: 'line',
          display_name: 'Line',
          color: '#3b82f6',
          category: 'line',
          icon: 'line',
          is_active: true,
        },
      ];

      await db.insert(annotationTypes).values(defaultTypes);
      return NextResponse.json({ message: 'Default types seeded successfully' });
    }

    // Regular create
    const { name, display_name, color, category, icon } = body;

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

    const result = await db
      .insert(annotationTypes)
      .values({
        name,
        display_name,
        color,
        category,
        icon: icon || null,
        is_active: true,
      })
      .returning();

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

// DELETE - Delete annotation type (only if no annotations use it)
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    const id = searchParams.get('id');

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

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

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

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

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

    await db.delete(annotationTypes).where(eq(annotationTypes.id, parseInt(id)));

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