import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import pino from 'pino';

const logger = pino({ name: 'api-runbooks' });

const createRunbookSchema = z.object({
  name: z.string().min(1).max(200),
  description: z.string().max(2000).optional(),
  yaml_content: z.string().min(1),
});

const listQuerySchema = z.object({
  page: z.coerce.number().min(1).default(1),
  limit: z.coerce.number().min(1).max(100).default(20),
  status: z.enum(['active', 'archived']).optional(),
});

export function registerRunbookRoutes(app: FastifyInstance) {
  // List runbooks
  app.get('/api/v1/runbooks', async (req, reply) => {
    const query = listQuerySchema.parse(req.query);
    // TODO: SELECT from runbooks with RLS tenant context
    return { runbooks: [], page: query.page, limit: query.limit, total: 0 };
  });

  // Get single runbook
  app.get('/api/v1/runbooks/:id', async (req, reply) => {
    const { id } = req.params as { id: string };
    // TODO: SELECT by id
    return { runbook: null };
  });

  // Create runbook
  app.post('/api/v1/runbooks', async (req, reply) => {
    const body = createRunbookSchema.parse(req.body);
    // TODO: INSERT into runbooks, parse YAML, validate steps
    logger.info({ name: body.name }, 'Runbook created');
    return reply.status(201).send({ id: 'placeholder', ...body });
  });

  // Trigger runbook execution
  app.post('/api/v1/runbooks/:id/execute', async (req, reply) => {
    const { id } = req.params as { id: string };
    const body = z.object({
      dry_run: z.boolean().default(false),
      variables: z.record(z.string()).optional(),
    }).parse(req.body ?? {});

    // TODO: Create execution record, dispatch to agent via WebSocket/queue
    logger.info({ runbookId: id, dryRun: body.dry_run }, 'Execution triggered');
    return reply.status(202).send({
      execution_id: 'placeholder',
      runbook_id: id,
      status: 'pending',
      dry_run: body.dry_run,
    });
  });

  // Get execution history
  app.get('/api/v1/runbooks/:id/executions', async (req, reply) => {
    const { id } = req.params as { id: string };
    // TODO: SELECT from executions
    return { executions: [] };
  });

  // Get execution detail (with step-by-step audit trail)
  app.get('/api/v1/executions/:executionId', async (req, reply) => {
    const { executionId } = req.params as { executionId: string };
    // TODO: SELECT execution + JOIN audit_entries
    return { execution: null, steps: [] };
  });
}
