/**
 * Extraction proxy routes — forward to extraction-service (port 4005).
 *
 * Hybrid approach: the Rust skills server handles local document processing
 * (PDF, xlsx, docx, pptx) inside the Docker sandbox, while extraction-service
 * provides AI-powered entity extraction and text analysis.
 *
 * This proxy lets the Tauri desktop access extraction-service via cowork-service.
 */

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

export async function extractionRoutes(app: FastifyInstance) {
  const extractionUrl = config.EXTRACTION_SERVICE_URL;

  // POST /api/extract — proxy to extraction-service POST /extract
  app.post('/api/extract', async (req, reply) => {
    try {
      const res = await fetch(`${extractionUrl}/extract`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
        body: JSON.stringify(req.body),
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Extraction service returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy extraction request');
      reply.code(502);
      return { error: 'Extraction service unavailable' };
    }
  });

  // GET /api/extract/models — list available extraction models
  app.get('/api/extract/models', async (req, reply) => {
    try {
      const res = await fetch(`${extractionUrl}/extract/models`, {
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Extraction service returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy extraction models');
      reply.code(502);
      return { error: 'Extraction service unavailable' };
    }
  });
}
