/**
 * Project budget route — project-hourly-budget spec.
 *
 * Mounted in routes/projects/index.ts (manifest.notes declares the required edit).
 *
 * GET /api/projects/:id/budget
 *   → { budget_hours, logged_hours, billable_hours, alert_pct, over_budget }
 *   Requires: projects:read
 *   Only returns data for hourly projects; returns 404 for non-hourly or missing.
 */
import { Hono } from 'hono'
import { getProjectBudgetSummary } from '@zync/db/queries'
import type { AppEnv } from '../../types'
import { requirePermission } from '../../middleware/guards'

export const projectBudgetRoute = new Hono<AppEnv>()

// GET /api/projects/:id/budget
projectBudgetRoute.get(
  '/:id/budget',
  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 tenantId = session.tid

    const summary = await getProjectBudgetSummary(db, tenantId, projectId)

    if (!summary) {
      return c.json({ error: 'Not found or project is not hourly' }, 404)
    }

    return c.json(summary, 200)
  },
)
