/**
 * Audit proxy routes — forward queries to platform-service GET /audit.
 *
 * These routes let the Tauri desktop app query centralized audit data
 * from platform-service via cowork-service, providing a REST alternative
 * to the local Rust IPC path for when the user is online.
 */

import type { FastifyInstance } from 'fastify';
import { config } from '../../lib/config.js';
import { PRODUCT_ID } from '../../lib/product-config.js';
import { AuditQuerySchema } from './types.js';

export async function auditRoutes(app: FastifyInstance) {
  const platformUrl = config.PLATFORM_SERVICE_URL;

  // GET /api/audit — proxy to platform-service GET /audit
  app.get('/api/audit', async (req, reply) => {
    const parsed = AuditQuerySchema.safeParse(req.query);
    if (!parsed.success) {
      reply.code(400);
      return { error: 'Invalid query', details: parsed.error.issues };
    }

    const { action, category, taskId, tool, days, limit, offset } = parsed.data;
    const params = new URLSearchParams();
    if (action) params.set('action', action);
    if (category) params.set('category', category);
    if (taskId) params.set('taskId', taskId);
    if (tool) params.set('tool', tool);
    params.set('days', String(days));
    params.set('limit', String(limit));
    params.set('offset', String(offset));

    try {
      const res = await fetch(`${platformUrl}/audit?${params}`, {
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy audit query to platform-service');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  // GET /api/audit/stats — proxy to platform-service GET /audit/stats
  app.get('/api/audit/stats', async (req, reply) => {
    const { days = '30' } = req.query as { days?: string };

    try {
      const res = await fetch(`${platformUrl}/audit/stats?days=${encodeURIComponent(days)}`, {
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy audit stats to platform-service');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });
}
