import type { FastifyInstance } from 'fastify';
import type { Sql } from '../db.js';

export function registerInboxRoutes(app: FastifyInstance, sql: Sql): void {
  // GET /api/inbox — tasks needing human attention (blocked or failed)
  app.get('/api/inbox', async () => {
    return sql`
      SELECT id, project_id, parent_task_id, state, input, output_summary, agent, model, session_id, started_at, ended_at, created_at
      FROM human_inbox
      ORDER BY created_at DESC
      LIMIT 100
    `;
  });

  // POST /api/inbox/:id/retry — reset a blocked/failed task to pending for re-dispatch
  app.post<{ Params: { id: string } }>('/api/inbox/:id/retry', async (req, reply) => {
    const taskId = req.params.id;

    const result = await sql`
      UPDATE tasks
      SET state = 'pending', started_at = NULL, ended_at = NULL, output_summary = NULL
      WHERE id = ${taskId} AND state IN ('blocked', 'failed')
      RETURNING id, state
    `;

    if (result.length === 0) {
      reply.code(404);
      return { error: 'task not found or not in retryable state' };
    }

    return { id: result[0]!.id, state: result[0]!.state };
  });
}
