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 { bridgeProvisionUserSchema } from './identity-bridge.schemas';
import { identityBridgeService } from './identity-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:',
  }),
  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/users',
  bridgeRateLimit,
  requireBridgeSecret,
  validate(bridgeProvisionUserSchema),
  async (req, res, next) => {
    try {
      const result = await identityBridgeService.provisionFromJsn(req.body);
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

export { router as identityBridgeRouter };
