const express = require('express');
const router = express.Router();
const db = require('../db');

// GET /api/authors/:username
router.get('/:username', (req, res) => {
  const { username } = req.params;
  try {
    const user = db.prepare(`
      SELECT username, full_name, avatar_url, twitter_url,
             COALESCE(NULLIF(full_name, ''), username) as display_name
      FROM users
      WHERE username = ?
    `).get(username);
    if (!user) return res.status(404).json({ error: 'Author not found' });
    res.json(user);
  } catch (err) {
    res.status(500).json({ error: 'Database error' });
  }
});

// GET /api/authors/:username/articles
router.get('/:username/articles', (req, res) => {
  const { username } = req.params;
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 12;
  const offset = (page - 1) * limit;

  try {
    const articles = db.prepare(`
      SELECT a.*, c.name as category_name, c.slug as category_slug
      FROM articles a
      JOIN categories c ON a.category_id = c.id
      JOIN users u ON a.user_id = u.id
      WHERE u.username = ? AND a.status = 'published'
      ORDER BY a.published_at DESC
      LIMIT ? OFFSET ?
    `).all(username, limit, offset);
    
    res.json({ articles });
  } catch (err) {
    res.status(500).json({ error: 'Database error' });
  }
});

module.exports = router;
