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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const chartId = parseInt(id, 10);

  if (isNaN(chartId)) {
    return NextResponse.json({ error: 'Invalid chart ID' }, { status: 400 });
  }

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

  return NextResponse.json(result[0]);
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const chartId = parseInt(id, 10);

  if (isNaN(chartId)) {
    return NextResponse.json({ error: 'Invalid chart ID' }, { status: 400 });
  }

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

  // Delete atomically in FK-safe order: spanAnnotations, annotations, candles, then chart
  await db.transaction(async (tx) => {
    await tx.delete(spanAnnotations).where(eq(spanAnnotations.chart_id, chartId));
    await tx.delete(annotations).where(eq(annotations.chart_id, chartId));
    await tx.delete(candles).where(eq(candles.chart_id, chartId));
    await tx.delete(charts).where(eq(charts.id, chartId));
  });

  return NextResponse.json({ success: true });
}
