import { Router, type Request, type Response, type NextFunction } from 'express';
import { timingSafeEqual } from 'node:crypto';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { redis } from '../../config/redis';
import { env } from '../../config/env';
import { validate } from '../../middleware/validate';
import { bridgeSocialLinksSchema } from './social-link-bridge.schemas';
import { socialLinkBridgeService } from './social-link-bridge.service';

const router = Router();

const bridgeRateLimit = rateLimit({
  windowMs: 60_000,
  max: 60,
  standardHeaders: true,
  legacyHeaders: false,
  store: new RedisStore({
    sendCommand: (command: string, ...args: string[]) =>
      redis.call(command, ...args) as Promise<any>,
    prefix: 'rl:bridge-social-links:',
  }),
  message: {
    error: { message: 'Bridge rate limit exceeded', code: 'BRIDGE_RATE_LIMIT' },
  },
});

function requireBridgeSecret(req: Request, res: Response, next: NextFunction) {
  if (!env.JSN_BRIDGE_SECRET) {
    return res.status(503).json({ error: 'BRIDGE_DISABLED' });
  }
  const header = req.get('authorization') ?? '';
  const expected = `Bearer ${env.JSN_BRIDGE_SECRET}`;
  const headerBuf = Buffer.from(header);
  const expectedBuf = Buffer.from(expected);
  if (
    headerBuf.length !== expectedBuf.length ||
    !timingSafeEqual(headerBuf, expectedBuf)
  ) {
    return res.status(401).json({ error: 'UNAUTHORIZED' });
  }
  next();
}

router.post(
  '/bridge/social-links',
  bridgeRateLimit,
  requireBridgeSecret,
  validate(bridgeSocialLinksSchema),
  async (req, res, next) => {
    try {
      const result = await socialLinkBridgeService.sync(req.body);
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

export { router as socialLinkBridgeRouter };
