/**
 * Admin analytics + reports routes — admin-dashboard.
 * GET /api/admin/reports/analytics → platform-level AI analytics (proxies system-ai)
 * GET /api/admin/reports/overview  → high-level billing/usage summary
 */
import { Hono } from 'hono'
import { z } from 'zod'
import { createDb } from '@zync/db/queries'
import {
  tokensByUseCase,
  costByTenant,
  errorRateByModel,
  costTrend,
} from '@zync/db/queries'
import type { AppEnv } from '../../types'
import { adminAuthMiddleware } from '../../middleware/admin-auth'
import { requireAdminSession } from '../../middleware/guards'
import { requireAdminPermission } from '@zync/auth'

const adminReportsRoutes = new Hono<AppEnv>()

adminReportsRoutes.use('*', adminAuthMiddleware)
adminReportsRoutes.use('*', requireAdminSession())
adminReportsRoutes.use('*', requireAdminPermission('admin.analytics:read'))

const PeriodQuerySchema = z.object({
  period: z
    .string()
    .regex(/^\d{4}-\d{2}$/)
    .optional(),
  months: z.coerce.number().int().positive().max(24).optional().default(6),
})

adminReportsRoutes.get('/analytics', async (c) => {
  const parsed = PeriodQuerySchema.safeParse(c.req.query())
  if (!parsed.success) {
    return c.json({ error: 'Invalid query params', details: parsed.error.flatten() }, 400)
  }

  const now = new Date()
  const defaultPeriod = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  const period = parsed.data.period ?? defaultPeriod

  const db = createDb(c.env)
  const [byUseCase, byTenant, byModel, trend] = await Promise.all([
    tokensByUseCase(db, period),
    costByTenant(db, period),
    errorRateByModel(db, period),
    costTrend(db, parsed.data.months),
  ])

  return c.json({
    period,
    tokensByUseCase: byUseCase,
    costByTenant: byTenant,
    errorRateByModel: byModel,
    costTrend: trend,
  })
})

adminReportsRoutes.get('/overview', async (c) => {
  // Platform-level billing overview — basic aggregation
  // Full billing integration is owned by billing module; this provides the shell
  return c.json({
    message: 'Billing overview available after billing module integration',
    generatedAt: new Date().toISOString(),
  })
})

export { adminReportsRoutes }
