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

// GET annotations scoped by chartId
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    let chartId = searchParams.get('chartId');

    // Fall back to most recent chart if no chartId provided
    if (!chartId) {
      const latest = await db.select({ id: charts.id }).from(charts).orderBy(desc(charts.created_at)).limit(1);
      if (latest.length === 0) {
        return NextResponse.json([]);
      }
      chartId = String(latest[0].id);
    }

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

    const allAnnotations = await db
      .select()
      .from(annotations)
      .where(eq(annotations.chart_id, chartIdNum));

    const normalized = allAnnotations.map((a) => ({
      ...a,
      timestamp: a.timestamp instanceof Date ? Math.floor(a.timestamp.getTime() / 1000) : a.timestamp,
    }));

    return NextResponse.json(normalized);
  } catch (error: any) {
    console.error(error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

// POST create new annotation (requires chart_id)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { timestamp, label_type, chart_id, geometry, color } = body;

    // Validate required fields
    if (!timestamp || !label_type || !chart_id) {
      return NextResponse.json(
        { error: 'timestamp, label_type, and chart_id are required' },
        { status: 400 }
      );
    }

    // Verify chart exists
    const chartExists = await db.select({ id: charts.id }).from(charts).where(eq(charts.id, chart_id)).limit(1);
    if (chartExists.length === 0) {
      return NextResponse.json(
        { error: 'Chart not found' },
        { status: 404 }
      );
    }

    // timestamp from client is Unix epoch seconds; convert to Date for Postgres
    const timestampDate = typeof timestamp === 'number'
      ? new Date(timestamp * 1000)
      : new Date(timestamp);

    const result = await db
      .insert(annotations)
      .values({
        chart_id,
        timestamp: timestampDate,
        label_type,
        geometry: geometry || null,
        color: color || '#3b82f6',
      })
      .returning();

    const row = result[0];
    return NextResponse.json({
      ...row,
      timestamp: row.timestamp instanceof Date ? Math.floor(row.timestamp.getTime() / 1000) : row.timestamp,
    }, { status: 201 });
  } catch (error: any) {
    console.error(error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

// DELETE annotations with bulk operations (scoped by chartId)
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    const type = searchParams.get('type');
    const all = searchParams.get('all');
    const chartId = searchParams.get('chartId');

    let result;

    if (all === 'true') {
      if (!chartId) {
        return NextResponse.json(
          { error: 'chartId is required for bulk delete' },
          { status: 400 }
        );
      }
      const chartIdNum = parseInt(chartId, 10);
      if (isNaN(chartIdNum)) {
        return NextResponse.json(
          { error: 'Invalid parameter: chartId must be an integer' },
          { status: 400 }
        );
      }
      result = await db.delete(annotations).where(eq(annotations.chart_id, chartIdNum)).returning();
    } else if (type) {
      const types = type.split(',').map((t) => t.trim());
      if (chartId) {
        const chartIdNum = parseInt(chartId, 10);
        if (isNaN(chartIdNum)) {
          return NextResponse.json(
            { error: 'Invalid parameter: chartId must be an integer' },
            { status: 400 }
          );
        }
        result = await db
          .delete(annotations)
          .where(and(inArray(annotations.label_type, types), eq(annotations.chart_id, chartIdNum)))
          .returning();
      } else {
        result = await db
          .delete(annotations)
          .where(inArray(annotations.label_type, types))
          .returning();
      }
    } else {
      return NextResponse.json(
        { error: 'Specify type or all parameter for bulk delete' },
        { status: 400 }
      );
    }

    return NextResponse.json({
      success: true,
      deleted: result.length,
    });
  } catch (error: any) {
    console.error(error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
