// backend/src/routes/content.js
import { Router } from 'express';
import { requireAuth, requireActive } from '../middleware/auth.js';
import { query } from '../utils/db.js';

const router = Router();

// GET /api/content  — paginated list
router.get('/', requireAuth, async (req, res) => {
  const { type, page = 1, limit = 20, date } = req.query;
  const offset = (parseInt(page) - 1) * Math.min(parseInt(limit), 50);

  let whereClause = 'WHERE user_id = $1';
  const params = [req.user.id];
  let paramIdx = 2;

  if (type) { whereClause += ` AND content_type = $${paramIdx++}`; params.push(type); }
  if (date) {
    whereClause += ` AND DATE(created_at) = $${paramIdx++}`;
    params.push(date);
  }

  const { rows: items } = await query(
    `SELECT id, content_type, title, created_at, metadata,
            SUBSTRING(body, 1, 200) as preview
     FROM generated_content ${whereClause}
     ORDER BY created_at DESC LIMIT $${paramIdx++} OFFSET $${paramIdx}`,
    [...params, Math.min(parseInt(limit), 50), offset]
  );

  const { rows: countRows } = await query(
    `SELECT COUNT(*) FROM generated_content ${whereClause}`,
    params
  );

  res.json({
    items,
    total: parseInt(countRows[0].count),
    page: parseInt(page),
    pages: Math.ceil(parseInt(countRows[0].count) / parseInt(limit))
  });
});

// GET /api/content/:id  — full content
router.get('/:id', requireAuth, async (req, res) => {
  const { rows } = await query(
    'SELECT * FROM generated_content WHERE id = $1 AND user_id = $2',
    [req.params.id, req.user.id]
  );
  if (!rows[0]) return res.status(404).json({ error: 'Content not found' });
  res.json(rows[0]);
});

// GET /api/content/:id/download  — download as .md file
router.get('/:id/download', requireAuth, async (req, res) => {
  const { rows } = await query(
    'SELECT * FROM generated_content WHERE id = $1 AND user_id = $2',
    [req.params.id, req.user.id]
  );
  if (!rows[0]) return res.status(404).json({ error: 'Content not found' });

  const item = rows[0];
  const filename = `${item.content_type}-${item.id.substring(0, 8)}.md`;
  res.setHeader('Content-Type', 'text/markdown');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
  res.send(`# ${item.title || item.content_type}\n\n${item.body}`);
});

// GET /api/content/stats/summary  — counts by type
router.get('/stats/summary', requireAuth, async (req, res) => {
  const { rows } = await query(
    `SELECT content_type, COUNT(*) as count,
            MAX(created_at) as last_generated
     FROM generated_content WHERE user_id = $1
     GROUP BY content_type`,
    [req.user.id]
  );
  res.json(rows);
});

// DELETE /api/content/:id
router.delete('/:id', requireAuth, async (req, res) => {
  const { rows } = await query(
    'DELETE FROM generated_content WHERE id = $1 AND user_id = $2 RETURNING id',
    [req.params.id, req.user.id]
  );
  if (!rows[0]) return res.status(404).json({ error: 'Content not found' });
  res.json({ success: true });
});

export default router;
