/* FutureMedia — routes.js
 * Defines POST /analyze and POST /download */

const express = require('express');
const downloader = require('./downloader');

const router = express.Router();

router.post('/analyze', async (req, res) => {
  const { url } = req.body;
  if (!url || typeof url !== 'string') {
    return res.status(400).json({ error: 'A valid "url" field is required.' });
  }

  try {
    const info = await downloader.analyze(url);
    res.json(info);
  } catch (err) {
    console.error('[analyze] failed:', err.message);
    res.status(500).json({ error: 'Analysis failed. Check the link and try again.' });
  }
});

router.post('/download', async (req, res) => {
  const { url, quality, type } = req.body;
  if (!url || typeof url !== 'string') {
    return res.status(400).json({ error: 'A valid "url" field is required.' });
  }

  // Stream progress back as newline-delimited JSON so the client can render
  // a live progress bar. If the client just wants a final result, it can
  // ignore intermediate lines and read the last one.
  res.setHeader('Content-Type', 'application/x-ndjson');

  try {
    const result = await downloader.download(url, { type, quality }, (progress) => {
      res.write(JSON.stringify({ status: 'progress', ...progress }) + '\n');
    });
    res.write(JSON.stringify({
      status: 'done',
      filename: result.filename,
      fileUrl: `/files/${encodeURIComponent(result.filename)}`,
    }) + '\n');
    res.end();
  } catch (err) {
    console.error('[download] failed:', err.message);
    res.write(JSON.stringify({ status: 'error', message: err.message }) + '\n');
    res.end();
  }
});

module.exports = router;
