import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';

export const GET: APIRoute = async () => {
  try {
    const stats = await query(`
      SELECT
        (SELECT COUNT(*) FROM products WHERE is_sneaker = true) as total_sneakers,
        (SELECT COUNT(*) FROM products) as total_products,
        (SELECT COUNT(*) FROM feeds WHERE is_enabled = true) as active_feeds,
        (SELECT COALESCE(SUM(clicks), 0) FROM daily_stats WHERE date = CURRENT_DATE AND dimension = 'total') as clicks_today,
        (SELECT COALESCE(SUM(revenue), 0) FROM daily_stats WHERE date >= DATE_TRUNC('month', CURRENT_DATE) AND dimension = 'total') as revenue_month,
        (SELECT MAX(last_sync_at) FROM feeds) as last_sync_at
    `);
    return new Response(JSON.stringify(stats.rows[0] || {}), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err: any) {
    return new Response(JSON.stringify({
      total_sneakers: 0, total_products: 0, active_feeds: 0,
      clicks_today: 0, revenue_month: 0, last_sync_at: null,
      error: err.message,
    }), {
      headers: { 'Content-Type': 'application/json' },
    });
  }
};
