/**
 * Fairness Audit API Routes
 */

import { Router } from 'express';
import { orchestrate, getAvailableOutputs } from '../services/fairness-orchestration/engine';
import type { OrchestrationRequest } from '../services/fairness-orchestration/engine';

const router = Router();

/**
 * GET /api/fairness/outputs
 * Get all available output types
 */
router.get('/outputs', (req, res) => {
  try {
    const outputs = getAvailableOutputs();
    res.json({ outputs });
  } catch (error) {
    res.status(500).json({ error: 'Failed to get output types' });
  }
});

/**
 * POST /api/fairness/orchestrate
 * Calculate orchestration for a request
 */
router.post('/orchestrate', (req, res) => {
  try {
    const request = req.body as OrchestrationRequest;
    
    // Validate request
    if (!request.input || !request.outputs || !request.timeline) {
      return res.status(400).json({ error: 'Invalid request: missing required fields' });
    }

    if (!request.input.dataset) {
      return res.status(400).json({ error: 'Invalid request: dataset is required' });
    }

    if (request.outputs.length === 0) {
      return res.status(400).json({ error: 'Invalid request: at least one output must be selected' });
    }

    const result = orchestrate(request);
    res.json(result);
  } catch (error) {
    const { logger } = await import('../lib/logger.js')
    logger.error('Orchestration error:', { error })
    res.status(500).json({ error: 'Failed to orchestrate request' })
  }
});

/**
 * POST /api/fairness/run
 * Start a fairness audit job
 */
router.post('/run', async (req, res) => {
  try {
    const request = req.body as OrchestrationRequest;
    
    // Validate and orchestrate
    const orchestration = orchestrate(request);
    
    if (!orchestration.feasible) {
      return res.status(400).json({
        error: 'Request is not feasible',
        orchestration
      });
    }

    // TODO: Create and queue actual job
    // For now, return job ID placeholder
    const jobId = `fairness-${Date.now()}`;
    
    res.json({
      jobId,
      status: 'queued',
      orchestration,
      estimatedCompletion: new Date(Date.now() + orchestration.estimatedTime * 1000).toISOString()
    });
  } catch (error) {
    console.error('Job creation error:', error);
    res.status(500).json({ error: 'Failed to create job' });
  }
});

/**
 * GET /api/fairness/jobs/:jobId
 * Get job status
 */
router.get('/jobs/:jobId', (req, res) => {
  try {
    const { jobId } = req.params;
    
    // TODO: Fetch actual job status
    res.json({
      jobId,
      status: 'running',
      progress: 0.5,
      estimatedCompletion: new Date(Date.now() + 3600000).toISOString()
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to get job status' });
  }
});

export default router;

