import { NextRequest, NextResponse } from 'next/server';
import { nocodbClient } from '@/api/nocodbClient';

/**
 * GET /api/admin/stats
 * Get dashboard statistics with optional time range filtering
 * Query params:
 *   - dateFrom: ISO date string (e.g., "2024-01-01")
 *   - dateTo: ISO date string
 *   - period: 'day' | 'week' | 'month' (for timeline data)
 */
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const dateFrom = searchParams.get('dateFrom') || undefined;
    const dateTo = searchParams.get('dateTo') || undefined;
    const period = (searchParams.get('period') || 'day') as 'day' | 'week' | 'month';

    // Get overall stats
    const stats = await nocodbClient.getStats(dateFrom, dateTo);

    // Get timeline data for charts
    const timeline = await nocodbClient.getOrdersTimeline(period, dateFrom, dateTo);

    return NextResponse.json({
      success: true,
      data: {
        stats,
        timeline,
      },
    });
  } catch (error) {
    console.error('Error fetching admin stats:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to fetch statistics',
      },
      { status: 500 }
    );
  }
}
