import { Hono } from 'hono'
import type { AppEnv } from '../../types'
import { requirePermission } from '../../middleware/guards'
import { getProjectAnalytics } from '@zync/db/queries'

export const projectAnalyticsRoutes = new Hono<AppEnv>()

function hasTenantWideProjectVisibility(role: string | null | undefined): boolean {
  return role === 'OWNER' || role === 'ADMIN' || role === 'VIEWER'
}

// GET /api/projects/:id/analytics
projectAnalyticsRoutes.get('/:id/analytics', requirePermission('projects:read'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const projectId = c.req.param('id')
  const db = c.get('db')
  const weeks = Math.max(1, Math.min(Number(c.req.query('weeks') ?? '8') || 8, 26))
  const analytics = await getProjectAnalytics(db, session.tid, projectId, {
    access: {
      fullVisibility: hasTenantWideProjectVisibility(session.role),
      userId: session.sub,
    },
    includeFinancials: session.permissions.includes('invoices:read'),
    weeks,
    tier: session.tier ?? null,
  })
  if (!analytics) return c.json({ error: 'Project not found' }, 404)
  return c.json({ analytics }, 200)
})
