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

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 allCandles = await db
      .select({
        time: candles.time,
        open: candles.open,
        high: candles.high,
        low: candles.low,
        close: candles.close,
      })
      .from(candles)
      .where(eq(candles.chart_id, chartIdNum))
      .orderBy(asc(candles.time));

    const normalized = allCandles.map((c) => ({
      ...c,
      time: c.time instanceof Date ? Math.floor(c.time.getTime() / 1000) : c.time,
    }));

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