import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { withTenant } from '../data/db.js';

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(['open', 'acknowledged', 'resolved', 'suppressed']).optional(),
  severity: z.enum(['critical', 'high', 'medium', 'low', 'info']).optional(),
  service: z.string().optional(),
});

export function registerIncidentRoutes(app: FastifyInstance) {
  // List incidents
  app.get('/api/v1/incidents', async (req, reply) => {
    const query = listQuerySchema.parse(req.query);
    const tenantId = (req as any).tenantId; // Set by auth middleware
    const offset = (query.page - 1) * query.limit;

    const result = await withTenant(tenantId, async (client) => {
      let sql = 'SELECT * FROM incidents WHERE 1=1';
      const params: any[] = [];
      let idx = 1;

      if (query.status) { sql += ` AND status = $${idx++}`; params.push(query.status); }
      if (query.severity) { sql += ` AND severity = $${idx++}`; params.push(query.severity); }
      if (query.service) { sql += ` AND service = $${idx++}`; params.push(query.service); }

      sql += ` ORDER BY created_at DESC LIMIT $${idx++} OFFSET $${idx++}`;
      params.push(query.limit, offset);

      return client.query(sql, params);
    });

    return { incidents: result.rows, page: query.page, limit: query.limit };
  });

  // Get incident detail with alerts
  app.get('/api/v1/incidents/:id', async (req, reply) => {
    const { id } = req.params as { id: string };
    const tenantId = (req as any).tenantId;

    const result = await withTenant(tenantId, async (client) => {
      const incident = await client.query('SELECT * FROM incidents WHERE id = $1', [id]);
      const alerts = await client.query('SELECT * FROM alerts WHERE incident_id = $1 ORDER BY received_at', [id]);
      return { incident: incident.rows[0] ?? null, alerts: alerts.rows };
    });

    if (!result.incident) return reply.status(404).send({ error: 'Not found' });
    return result;
  });

  // Acknowledge incident
  app.post('/api/v1/incidents/:id/acknowledge', async (req, reply) => {
    const { id } = req.params as { id: string };
    const tenantId = (req as any).tenantId;

    await withTenant(tenantId, async (client) => {
      await client.query("UPDATE incidents SET status = 'acknowledged' WHERE id = $1 AND status = 'open'", [id]);
    });

    return { status: 'acknowledged' };
  });

  // Resolve incident
  app.post('/api/v1/incidents/:id/resolve', async (req, reply) => {
    const { id } = req.params as { id: string };
    const tenantId = (req as any).tenantId;

    await withTenant(tenantId, async (client) => {
      await client.query("UPDATE incidents SET status = 'resolved', resolved_at = now() WHERE id = $1", [id]);
    });

    return { status: 'resolved' };
  });

  // Suppress incident (snooze)
  app.post('/api/v1/incidents/:id/suppress', async (req, reply) => {
    const { id } = req.params as { id: string };
    const tenantId = (req as any).tenantId;

    await withTenant(tenantId, async (client) => {
      await client.query("UPDATE incidents SET status = 'suppressed' WHERE id = $1", [id]);
    });

    return { status: 'suppressed' };
  });

  // Dashboard summary
  app.get('/api/v1/summary', async (req, reply) => {
    const tenantId = (req as any).tenantId;

    const result = await withTenant(tenantId, async (client) => {
      const counts = await client.query(`
        SELECT status, severity, COUNT(*)::int as count
        FROM incidents
        WHERE created_at > now() - interval '24 hours'
        GROUP BY status, severity
      `);
      const total = await client.query(`SELECT COUNT(*)::int as total FROM incidents WHERE status = 'open'`);
      return { breakdown: counts.rows, open_total: total.rows[0]?.total ?? 0 };
    });

    return result;
  });
}
