/**
 * Auto-Trigger Routes — Remote Diagnostics Phase 4
 * Admin endpoints for configuring automated debug session triggers.
 */

import type { FastifyInstance } from 'fastify';
import { requireRole } from '../../lib/auth.js';
import {
  createTriggerConfig,
  getTriggerConfig,
  listTriggerConfigs,
  updateTriggerConfig,
  deleteTriggerConfig,
  runAllTriggers,
  type TriggerConfig,
  CreateTriggerConfigSchema,
} from './auto-triggers.js';

export async function autoTriggerRoutes(app: FastifyInstance): Promise<void> {
  // List all triggers for a product (admin only)
  app.get('/diagnostics/triggers', async (req, reply) => {
    await requireRole(req, 'admin');

    const { productId } = req.query as { productId?: string };
    if (!productId) {
      return reply.status(400).send({ error: 'productId required' });
    }

    const triggers = await listTriggerConfigs(productId);
    return { triggers };
  });

  // Create new trigger (admin only)
  app.post('/diagnostics/triggers', async (req, reply) => {
    await requireRole(req, 'admin');

    const result = CreateTriggerConfigSchema.safeParse(req.body);
    if (!result.success) {
      return reply.status(400).send({
        error: 'Invalid trigger config',
        details: result.error.issues,
      });
    }

    const trigger = await createTriggerConfig(result.data);
    app.log.info(`Auto-trigger created: ${trigger.id} for product ${trigger.productId}`);

    return reply.status(201).send({ trigger });
  });

  // Get trigger details (admin only)
  app.get('/diagnostics/triggers/:id', async (req, reply) => {
    await requireRole(req, 'admin');

    const { id } = req.params as { id: string };
    const trigger = await getTriggerConfig(id);

    if (!trigger) {
      return reply.status(404).send({ error: 'Trigger not found' });
    }

    return { trigger };
  });

  // Update trigger (admin only)
  app.patch('/diagnostics/triggers/:id', async (req, reply) => {
    await requireRole(req, 'admin');

    const { id } = req.params as { id: string };

    const updated = await updateTriggerConfig(id, req.body as Partial<TriggerConfig>);
    if (!updated) {
      return reply.status(404).send({ error: 'Trigger not found' });
    }

    app.log.info(`Auto-trigger updated: ${id}`);
    return { trigger: updated };
  });

  // Delete trigger (admin only)
  app.delete('/diagnostics/triggers/:id', async (req, reply) => {
    await requireRole(req, 'admin');

    const { id } = req.params as { id: string };

    const deleted = await deleteTriggerConfig(id);
    if (!deleted) {
      return reply.status(404).send({ error: 'Trigger not found' });
    }

    app.log.info(`Auto-trigger deleted: ${id}`);
    return reply.status(204).send();
  });

  // Manually run all triggers for a product (admin only)
  app.post('/diagnostics/triggers/run', async (req, reply) => {
    await requireRole(req, 'admin');

    const { productId } = req.body as { productId: string };
    const userId = req.jwtPayload?.sub ?? 'system';

    if (!productId) {
      return reply.status(400).send({ error: 'productId required' });
    }

    const results = await runAllTriggers(productId, userId);
    return { results };
  });
}
