/**
 * Reports hub routes — reports-navigation-hub (wave-13, spec 103).
 * Mounted at /api/reports in the main reports router.
 *
 * Routes:
 *   GET  /reports/summary                — aggregate KPI summary for all tiles
 *   GET  /reports/shortcuts              — list user's saved shortcuts
 *   POST /reports/shortcuts              — create a saved shortcut
 *   DELETE /reports/shortcuts/:id        — delete a saved shortcut (own only)
 *
 * Access: requires reports:read permission.
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission } from '../../middleware/guards'
import {
  createDb,
  listReportShortcuts,
  createReportShortcut,
  deleteReportShortcut,
  getReportsSummary,
  createReportShortcutInputSchema,
} from '@zync/db/queries'

export const reportsHubRoutes = new Hono<AppEnv>()

reportsHubRoutes.use('*', authMiddleware)
reportsHubRoutes.use('*', requirePermission('reports:read'))

// ── Date range schema ────────────────────────────────────────────────────────

const dateRangeSchema = z.object({
  from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
  to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
})

function thisMonthRange(): { from: string; to: string } {
  const now = new Date()
  const from = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10)
  const to = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().slice(0, 10)
  return { from, to }
}

// ── GET /reports/summary ─────────────────────────────────────────────────────

reportsHubRoutes.get('/summary', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }

  const parsed = dateRangeSchema.safeParse(c.req.query())
  if (!parsed.success) {
    return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)
  }

  const defaults = thisMonthRange()
  const from = parsed.data.from ?? defaults.from
  const to = parsed.data.to ?? defaults.to

  // Determine scope: MEMBER sees own stats only; ADMIN/OWNER see org-wide
  const role = (session as { role?: string }).role?.toLowerCase() ?? 'member'
  const scope: 'own' | 'org' = (role === 'owner' || role === 'admin') ? 'org' : 'own'

  const db = createDb(c.env)
  const summary = await getReportsSummary(
    db,
    c.env,
    session.tid,
    { scope, userId: session.sub },
    from,
    to,
  )

  return c.json(summary, 200)
})

// ── GET /reports/shortcuts ───────────────────────────────────────────────────

reportsHubRoutes.get('/shortcuts', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }

  const db = createDb(c.env)
  const items = await listReportShortcuts(db, session.tid, session.sub)

  return c.json({ items }, 200)
})

// ── POST /reports/shortcuts ──────────────────────────────────────────────────

reportsHubRoutes.post('/shortcuts', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }

  const body = await c.req.json().catch(() => null)
  const parsed = createReportShortcutInputSchema.safeParse(body)
  if (!parsed.success) {
    return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)
  }

  const db = createDb(c.env)
  const shortcut = await createReportShortcut(db, session.tid, session.sub, parsed.data)

  return c.json(shortcut, 201)
})

// ── DELETE /reports/shortcuts/:id ────────────────────────────────────────────

reportsHubRoutes.delete('/shortcuts/:id', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }

  const id = c.req.param('id')
  const db = createDb(c.env)
  const deleted = await deleteReportShortcut(db, session.tid, session.sub, id)

  if (!deleted) {
    return c.json({ error: 'Shortcut not found' }, 404)
  }

  return c.json({ ok: true }, 200)
})
