'use strict';

const express = require('express');
const router = express.Router();
const {
  buildCalendarFeed,
  getTokenRecord,
  markTokenUsed,
} = require('../services/calendarFeedService');

// GET /api/calendar/feed.ics?token=...
// Public by design: calendar clients cannot use the app's session cookies.
router.get('/feed.ics', (req, res) => {
  const token = String(req.query.token || '');
  const tokenRow = getTokenRecord(token);
  if (!tokenRow) {
    return res.status(404).type('text/plain').send('Calendar feed not found or revoked.');
  }

  const { ics } = buildCalendarFeed(tokenRow.user_id, {
    name: tokenRow.label || 'Bill Tracker',
  });
  markTokenUsed(tokenRow.id);

  res.status(200);
  res.set({
    'Content-Type': 'text/calendar; charset=utf-8',
    'Content-Disposition': 'inline; filename="bill-tracker.ics"',
    'Cache-Control': 'private, max-age=300',
  });
  return res.send(ics);
});

module.exports = router;
