import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { listmonkClient } from '../../services/listmonk.client';
import { listmonkSyncService } from '../../services/listmonk-sync.service';
import { listmonkEventSyncService } from '../../services/listmonk-event-sync.service';
import { env } from '../../config/env';
import { BROADCAST_ROLES } from '../../utils/roles';

const router = Router();
router.use(authenticate);
router.use(requireRole(...BROADCAST_ROLES));

// GET /api/listmonk — sync status
router.get(
  '/',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const status = listmonkSyncService.getStatus();
      // Live connection check
      const connected = await listmonkClient.checkHealth();
      res.json({ ...status, connected });
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/listmonk/stats — list subscriber counts
router.get(
  '/stats',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const stats = await listmonkSyncService.getStats();
      res.json(stats);
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/listmonk/test-connection
router.post(
  '/test-connection',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const healthy = await listmonkClient.checkHealth();
      res.json({
        success: healthy,
        message: healthy ? 'Listmonk is reachable' : 'Listmonk is not reachable',
      });
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/listmonk/sync/participants
router.post(
  '/sync/participants',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const results = await listmonkSyncService.syncCampaignParticipants();
      listmonkSyncService.setLastSyncAt(new Date());
      res.json({
        success: true,
        message: `Synced ${results.success}/${results.total} campaign participants`,
        results,
      });
    } catch (err) {
      listmonkSyncService.setLastError(err instanceof Error ? err.message : String(err));
      next(err);
    }
  },
);

// POST /api/listmonk/sync/locations
router.post(
  '/sync/locations',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const results = await listmonkSyncService.syncLocations();
      listmonkSyncService.setLastSyncAt(new Date());
      res.json({
        success: true,
        message: `Synced ${results.success}/${results.total} locations`,
        results,
      });
    } catch (err) {
      listmonkSyncService.setLastError(err instanceof Error ? err.message : String(err));
      next(err);
    }
  },
);

// POST /api/listmonk/sync/users
router.post(
  '/sync/users',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const results = await listmonkSyncService.syncUsers();
      listmonkSyncService.setLastSyncAt(new Date());
      res.json({
        success: true,
        message: `Synced ${results.success}/${results.total} users`,
        results,
      });
    } catch (err) {
      listmonkSyncService.setLastError(err instanceof Error ? err.message : String(err));
      next(err);
    }
  },
);

// POST /api/listmonk/sync/all
router.post(
  '/sync/all',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const results = await listmonkSyncService.syncAll();
      res.json({
        success: true,
        message: 'All syncs completed',
        results,
      });
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/listmonk/reinitialize
router.post(
  '/reinitialize',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      await listmonkSyncService.reinitialize();
      res.json({ success: true, message: 'Lists reinitialized' });
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/listmonk/event-sync-stats — event-driven sync stats
router.get(
  '/event-sync-stats',
  (_req: Request, res: Response) => {
    res.json(listmonkEventSyncService.getStats());
  },
);

// GET /api/listmonk/proxy-url — get proxy port + token for iframe embedding
router.get(
  '/proxy-url',
  (req: Request, res: Response, _next: NextFunction) => {
    const token = req.headers.authorization?.slice(7) || '';
    res.json({ port: env.LISTMONK_PROXY_PORT, token });
  },
);

export { router as listmonkRouter };
