// @ts-nocheck — route controller converted to .cts; handler req/res typed, full type-check deferred (thin glue over typed services).
import type { Req, Res, Next } from '../types/http';
('use strict');

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

// GET /api/calendar/feed.ics?token=...
// Public by design: calendar clients cannot use the app's session cookies.
router.get('/feed.ics', (req: Req, res: 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;
