const express = require('express');
const router = express.Router();
const { getTracker, getUpcomingBills, getOverdueCount } = require('../services/trackerService');
const { standardizeError } = require('../middleware/errorFormatter');

// GET /api/tracker/overdue-count — lightweight count for sidebar badge
router.get('/overdue-count', (req, res) => {
  try {
    res.json(getOverdueCount(req.user.id));
  } catch (err) {
    console.error('[tracker/overdue-count]', err.message);
    res.status(500).json(standardizeError('Failed to load overdue count', 'INTERNAL_ERROR'));
  }
});

// GET /api/tracker?year=2026&month=5
router.get('/', (req, res) => {
  try {
    const result = getTracker(req.user.id, req.query);
    if (result.error) {
      return res.status(result.status || 400).json(standardizeError(result.error, 'VALIDATION_ERROR'));
    }
    res.json(result);
  } catch (err) {
    console.error('[tracker]', err.message);
    res.status(500).json(standardizeError('Failed to load tracker data', 'INTERNAL_ERROR'));
  }
});

// GET /api/tracker/upcoming?days=30
router.get('/upcoming', (req, res) => {
  try {
    res.json(getUpcomingBills(req.user.id, req.query));
  } catch (err) {
    console.error('[tracker/upcoming]', err.message);
    res.status(500).json(standardizeError('Failed to load upcoming bills', 'INTERNAL_ERROR'));
  }
});

module.exports = router;
