// ═══════════════════════════════════════════════════════════
// Feedback Routes — POST /v1/feedback, GET /v1/feedback
// Bridges modals → API → learning pipeline
// ═══════════════════════════════════════════════════════════

import { Hono } from 'hono';

const feedback = new Hono();

// POST /v1/feedback — Submit a feedback event from a modal
feedback.post('/', async (c) => {
  const body = await c.req.json();

  // Basic validation — the learning package handles full schema validation
  if (!body || typeof body !== 'object') {
    return c.json({
      ok: false,
      error: {
        code: 'BAD_REQUEST',
        message: 'Invalid feedback payload',
        requestId: c.req.header('X-Request-Id') || crypto.randomUUID(),
      },
    }, 400);
  }

  // Generate an ID if not provided
  const id = body.id || crypto.randomUUID();
  const timestamp = body.timestamp || new Date().toISOString();

  // TODO: In production, this would:
  // 1. Publish to Redis Stream (factory.feedback)
  // 2. The learning pipeline consumer picks it up
  // 3. Validate → Enrich → Store → Analyze → Act
  //
  // For now, we accept and acknowledge

  // Publish event for WebSocket subscribers
  // await publishEvent('feedback.received', {
  //   feedbackId: id,
  //   pipelineId: body.pipelineId || null,
  //   modalType: body.modalType || 'unknown',
  //   decision: body.feedback?.decision?.decision || null,
  // });

  return c.json({
    ok: true,
    data: { id, timestamp },
  }, 201);
});

// GET /v1/feedback — List feedback events
feedback.get('/', async (c) => {
  const pipelineId = c.req.query('pipelineId');
  const modalType = c.req.query('modalType');
  const since = c.req.query('since');
  const decision = c.req.query('decision');
  const page = parseInt(c.req.query('page') || '1', 10);
  const limit = Math.min(parseInt(c.req.query('limit') || '20', 10), 100);

  // TODO: Query from feedback storage (JSONL or database)
  // For now return empty list
  return c.json({
    ok: true,
    data: [],
    meta: {
      requestId: c.req.header('X-Request-Id') || crypto.randomUUID(),
      timestamp: new Date().toISOString(),
      pagination: {
        page,
        limit,
        total: 0,
        totalPages: 0,
        hasNext: false,
        hasPrev: false,
      },
    },
  });
});

// GET /v1/feedback/stats — Feedback statistics
feedback.get('/stats', async (c) => {
  // TODO: Pull from learning pipeline's analysis results
  return c.json({
    ok: true,
    data: {
      totalEvents: 0,
      last30Days: {
        approvalRate: 0,
        avgQualityScore: 0,
        avgTimeToDecisionMs: 0,
        predictionAccuracy: 0,
        autoApproveRate: 0,
        feedbackVolume: 0,
      },
      trends: {
        approvalRate: 'stable',
        qualityScore: 'stable',
        decisionSpeed: 'stable',
      },
      activeRules: 0,
      autonomyLevels: {},
    },
  });
});

export { feedback as feedbackRouter };
