import express from 'express';
import { CampaignsService } from '../../services/klaviyo/campaigns.service.js';
import { TimeManager } from '../../../shared/business-time/index.js';

export function createCampaignsRouter(apiKey, apiRevision, redis) {
  const router = express.Router();
  const timeManager = new TimeManager();
  const campaignsService = new CampaignsService(apiKey, apiRevision, redis);

  // Get campaigns with optional filtering
  router.get('/', async (req, res) => {
    try {
      const params = {
        pageSize: parseInt(req.query.pageSize) || 50,
        sort: req.query.sort || '-send_time',
        status: req.query.status,
        startDate: req.query.startDate,
        endDate: req.query.endDate,
        pageCursor: req.query.pageCursor
      };

      console.log('[Campaigns Route] Fetching campaigns with params:', params);
      const data = await campaignsService.getCampaigns(params);
      console.log('[Campaigns Route] Success:', {
        count: data.data?.length || 0
      });
      res.json(data);
    } catch (error) {
      console.error('[Campaigns Route] Error:', error);
      res.status(500).json({ 
        status: 'error', 
        message: error.message,
        details: error.response?.data || null
      });
    }
  });

  // Get campaigns by time range
  router.get('/:timeRange', async (req, res) => {
    try {
      const { timeRange } = req.params;
      const { status } = req.query;

      let result;
      if (timeRange === 'custom') {
        const { startDate, endDate } = req.query;
        if (!startDate || !endDate) {
          return res.status(400).json({ error: 'Custom range requires startDate and endDate' });
        }

        result = await campaignsService.getCampaigns({
          startDate,
          endDate,
          status
        });
      } else {
        result = await campaignsService.getCampaignsByTimeRange(
          timeRange,
          { status }
        );
      }

      res.json(result);
    } catch (error) {
      console.error("[Campaigns Route] Error:", error);
      res.status(500).json({ error: error.message });
    }
  });

  return router;
} 