// backend/src/routes/pipeline.js
import { Router } from 'express';
import { requireAuth, requireActive } from '../middleware/auth.js';
import { enqueuePipeline, pipelineQueue } from '../jobs/pipeline-worker.js';
import { query } from '../utils/db.js';
import { checkPipelineAllowed } from '../utils/limits.js';

const router = Router();

// POST /api/pipeline/run  — trigger manual run (auto-generates topics)
router.post('/run', requireAuth, requireActive, async (req, res) => {
  try {
    const check = await checkPipelineAllowed(req.user.id);
    if (!check.allowed) return res.status(check.status).json(check.payload);

    const jobId = await enqueuePipeline(req.user.id, 'manual');
    res.json({ success: true, jobId, runsRemaining: check.remaining });
  } catch (err) {
    res.status(500).json({ error: 'Failed to start pipeline', message: err.message });
  }
});

// GET /api/pipeline/status  — current run status
router.get('/status', requireAuth, async (req, res) => {
  const { rows } = await query(
    `SELECT id, status, triggered_by, agents_run, scripts_count, error_message, started_at, completed_at, created_at
     FROM pipeline_runs WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1`,
    [req.user.id]
  );
  if (!rows[0]) return res.json({ status: 'never_run' });
  res.json(rows[0]);
});

// GET /api/pipeline/history  — past runs
router.get('/history', requireAuth, async (req, res) => {
  const limit = Math.min(parseInt(req.query.limit) || 20, 100);
  const { rows } = await query(
    `SELECT id, status, triggered_by, agents_run, scripts_count, error_message, started_at, completed_at, created_at
     FROM pipeline_runs WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`,
    [req.user.id, limit]
  );
  res.json(rows);
});

// GET /api/pipeline/job/:jobId  — BullMQ job progress
router.get('/job/:jobId', requireAuth, async (req, res) => {
  try {
    const job = await pipelineQueue.getJob(req.params.jobId);
    if (!job) return res.status(404).json({ error: 'Job not found' });
    const state = await job.getState();
    const progress = job.progress;
    res.json({ state, progress, result: job.returnvalue, failedReason: job.failedReason });
  } catch (err) {
    res.status(500).json({ error: 'Failed to get job status' });
  }
});

export default router;
