import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { NextResponse } from 'next/server'

/**
 * GET /api/admin/recent-orders
 * Gibt die letzten 10 Bestellungen und Umsatzdaten der letzten 6 Monate zurück.
 * Wird vom Admin-Dashboard alle 30 Sekunden gepollt.
 * Zugriff nur für authentifizierte User mit Admin-Rolle (bypasses RLS).
 */
export async function GET() {
  const supabase = await createClient()

  // Session prüfen
  const { data: { user }, error: authError } = await supabase.auth.getUser()
  if (authError || !user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Admin-Rolle prüfen
  const { data: userData } = await supabase
    .from('users')
    .select('role')
    .eq('id', user.id)
    .single()

  if (!userData || userData.role !== 'admin') {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const adminDb = createAdminClient()

  // 1. Letzte 10 Bestellungen laden
  const { data: orders, error } = await adminDb
    .from('orders')
    .select('id, order_number, created_at, total_price, status, customer_data')
    .order('created_at', { ascending: false })
    .limit(10)

  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }

  // 2. Umsatzdaten der letzten 6 Monate für das Chart ermitteln
  const sixMonthsAgo = new Date()
  sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5)
  sixMonthsAgo.setDate(1)
  sixMonthsAgo.setHours(0, 0, 0, 0)

  const { data: chartOrders, error: chartError } = await adminDb
    .from('orders')
    .select('total_price, created_at')
    .neq('status', 'cancelled')
    .gte('created_at', sixMonthsAgo.toISOString())

  let chartData: { name: string; value: number }[] = []
  if (!chartError && chartOrders) {
    const monthlyData: Record<string, number> = {}
    const now = new Date()

    // Die letzten 6 Monate initialisieren
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const key = d.toLocaleDateString('de-DE', { month: 'short', year: '2-digit' })
      monthlyData[key] = 0
    }

    // Werte aufsummieren
    chartOrders.forEach(o => {
      const date = new Date(o.created_at)
      const key = date.toLocaleDateString('de-DE', { month: 'short', year: '2-digit' })
      if (key in monthlyData) {
        monthlyData[key] += Number(o.total_price)
      }
    })

    // In Array umwandeln
    chartData = Object.entries(monthlyData).map(([name, value]) => ({
      name,
      value: Math.round(value * 100) / 100
    }))
  } else if (chartError) {
    console.error('Chart data fetch error:', chartError)
  }

  return NextResponse.json({ orders, chartData })
}
