// app/api/candles/route.ts
import { NextResponse } from 'next/server';
import yahooFinance from 'yahoo-finance2';

// Valid intervals for yahoo-finance2
const VALID_INTERVALS = ['1m', '2m', '5m', '15m', '30m', '60m', '90m', '1h', '1d', '5d', '1wk', '1mo', '3mo'] as const;
type ValidInterval = typeof VALID_INTERVALS[number];

function isValidInterval(interval: string): interval is ValidInterval {
  return VALID_INTERVALS.includes(interval as ValidInterval);
}

function getMillisecondsForInterval(interval: ValidInterval, count: number): number {
  const intervalToMs: Record<ValidInterval, number> = {
    '1m': 60 * 1000,
    '2m': 2 * 60 * 1000,
    '5m': 5 * 60 * 1000,
    '15m': 15 * 60 * 1000,
    '30m': 30 * 60 * 1000,
    '60m': 60 * 60 * 1000,
    '90m': 90 * 60 * 1000,
    '1h': 60 * 60 * 1000,
    '1d': 24 * 60 * 60 * 1000,
    '5d': 5 * 24 * 60 * 60 * 1000,
    '1wk': 7 * 24 * 60 * 60 * 1000,
    '1mo': 30 * 24 * 60 * 60 * 1000,
    '3mo': 90 * 24 * 60 * 60 * 1000,
  };

  return intervalToMs[interval] * count;
}

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const symbol = searchParams.get('symbol') || 'BBCA.JK';
    const intervalParam = searchParams.get('interval') || '1d';
    const count = Math.min(parseInt(searchParams.get('count') || '100'), 500); // Limit to 500 max
    const endParam = searchParams.get('end');

    console.log('API Request:', { symbol, interval: intervalParam, count, end: endParam });

    // Validate interval
    if (!isValidInterval(intervalParam)) {
      return NextResponse.json(
        { error: `Invalid interval. Valid intervals: ${VALID_INTERVALS.join(', ')}` },
        { status: 400 }
      );
    }

    const interval = intervalParam as ValidInterval;

    // Calculate date range
    let endDate: Date;
    let startDate: Date;

    if (endParam) {
      // For pagination (loading more historical data)
      endDate = new Date(endParam);
      if (isNaN(endDate.getTime())) {
        return NextResponse.json({ error: 'Invalid end date format' }, { status: 400 });
      }
    } else {
      // For initial load (current data)
      endDate = new Date();
    }

    // Calculate start date based on interval and count
    const timespan = getMillisecondsForInterval(interval, count);
    startDate = new Date(endDate.getTime() - timespan);

    // Add some buffer for weekends/holidays (especially for daily data)
    if (interval === '1d' || interval === '5d' || interval === '1wk') {
      startDate = new Date(startDate.getTime() - (7 * 24 * 60 * 60 * 1000)); // Add 7 days buffer
    }

    // Fetch data from Yahoo Finance
    const results = await yahooFinance.historical(symbol, {
      period1: startDate,
      period2: endDate,
      interval: interval,
    });


    if (!results || results.length === 0) {
      return NextResponse.json(
        { error: 'No data found for the specified symbol and time range' },
        { status: 404 }
      );
    }

    // Process and format the data
    const candles = results
      .filter(d => d.date && d.open && d.high && d.low && d.close) // Filter out incomplete data
      .map((d) => ({
        time: Math.floor(new Date(d.date).getTime() / 1000), // Unix timestamp in seconds
        open: Number(d.open),
        high: Number(d.high),
        low: Number(d.low),
        close: Number(d.close),
        volume: d.volume ? Number(d.volume) : 0,
      }))
      .sort((a, b) => a.time - b.time) // Sort by time ascending
      .slice(-count); // Take only the requested number of candles


    // Validate that we have reasonable data
    if (candles.length === 0) {
      return NextResponse.json(
        { error: 'No valid candle data found' },
        { status: 404 }
      );
    }

    return NextResponse.json(candles);

  } catch (error) {
    console.error('API Error:', error);
    
    // Provide more specific error messages
    if (error instanceof Error) {
      if (error.message.includes('404')) {
        return NextResponse.json(
          { error: `Symbol "${searchParams?.get('symbol')}" not found` },
          { status: 404 }
        );
      }
      if (error.message.includes('timeout')) {
        return NextResponse.json(
          { error: 'Request timeout - please try again' },
          { status: 408 }
        );
      }
    }

    return NextResponse.json(
      { error: 'Failed to fetch data from Yahoo Finance' },
      { status: 500 }
    );
  }
}