import { Router } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { SOCIAL_ROLES } from '../../utils/roles';
import { friendshipRouter } from './friendship.routes';
import { blockRouter } from './block.routes';
import { privacyRouter } from './privacy.routes';
import { notificationRouter } from './notification.routes';
import { profileRouter } from './profile.routes';
import { feedRouter } from './feed.routes';
import { suggestionsRouter } from './suggestions.routes';
import { pokeRouter } from './poke.routes';
import { recommendationRouter } from './recommendation.routes';
import { integrationRouter } from './integration.routes';
import { groupRouter } from './group.routes';
import { achievementsRouter } from './achievements.routes';
import { sseRouter } from './sse.routes';
import { socialAdminRouter } from './social-admin.routes';
import { referralRouter } from './referral.routes';
import { impactStoriesRouter } from './impact-stories.routes';
import { spotlightRouter } from './spotlight.routes';
import { challengeRouter } from './challenge.routes';

const router = Router();

// EventSource SSE auth: accepts signed URL params (`?sig=&exp=&uid=`) and
// synthesizes an Authorization header so downstream `authenticate` middleware
// can treat the caller as header-authenticated. The legacy `?token=<JWT>` path
// was removed on 2026-04-12 — full JWTs in URLs leak via logs/referer; signed
// URLs are path-scoped and 5-min TTL.
router.use(async (req, _res, next) => {
  if (
    !req.headers.authorization &&
    req.path.startsWith('/sse') &&
    req.query.sig && req.query.exp && req.query.uid
  ) {
    const { verifyMediaSignature } = await import('../../utils/signed-url');
    const result = verifyMediaSignature(
      req.originalUrl || req.url,
      req.query as Record<string, string | undefined>
    );
    if (result.valid) {
      // Forge a short-lived access token so downstream authenticate() works
      // unchanged. Better architecturally would be a dedicated 'signed auth'
      // middleware, but synthesizing here keeps the blast-radius tiny.
      const jwt = await import('jsonwebtoken');
      const { env } = await import('../../config/env');
      const { prisma } = await import('../../config/database');
      const user = await prisma.user.findUnique({
        where: { id: result.userId },
        select: { id: true, email: true, role: true, roles: true, status: true },
      });
      if (user && user.status === 'ACTIVE') {
        const token = jwt.sign(
          { id: user.id, email: user.email, role: user.role, roles: user.roles },
          env.JWT_ACCESS_SECRET,
          { algorithm: 'HS256', expiresIn: '5m' }
        );
        req.headers.authorization = `Bearer ${token}`;
      }
    }
  }
  next();
});

// All social routes require authentication
router.use(authenticate);

// Admin sub-router (requires admin role)
router.use('/admin', requireRole(...SOCIAL_ROLES), socialAdminRouter);

// Sub-routers
router.use('/friends', friendshipRouter);
router.use('/blocks', blockRouter);
router.use('/privacy', privacyRouter);
router.use('/notifications', notificationRouter);
router.use('/profile', profileRouter);
router.use('/feed', feedRouter);
router.use('/suggestions', suggestionsRouter);
router.use('/pokes', pokeRouter);
router.use('/recommendations', recommendationRouter);
router.use('/integration', integrationRouter);
router.use('/groups', groupRouter);
router.use('/achievements', achievementsRouter);
router.use('/sse', sseRouter);
router.use('/referrals', referralRouter);
router.use('/stories', impactStoriesRouter);
router.use('/spotlight', spotlightRouter);
router.use('/challenges', challengeRouter);

export { router as socialRouter };
