/* eslint-disable import/prefer-default-export */
import type { NextFunction, Request, Response } from 'express';
import { verify } from '@blocklet/sdk/lib/util/verify-sign';
import { translate } from '../locales';
import { context } from './context';

export function ensureI18n() {
  return (req: Request, _: Response, next: NextFunction) => {
    req.locale = String(req.query.locale || 'en');
    req.t = translate;
    next();
  };
}

export async function contextMiddleware(req: Request, _res: Response, next: NextFunction) {
  const requestId =
    (req.headers['x-request-id'] as string) || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
  let requestedBy = 'system';

  // Check component signature
  const sig = req.get('x-component-sig');
  const componentDid = req.get('x-component-did');
  if (sig && componentDid) {
    const data = typeof req.body === 'undefined' ? {} : req.body;
    const verified = await verify(data, sig);
    if (verified) {
      requestedBy = componentDid;
    }
  }

  // Check user DID from headers
  if (req.headers['x-user-did']) {
    requestedBy = req.headers['x-user-did'] as string;
  }

  // Check authenticated user
  if (req.user?.did) {
    requestedBy = req.user.did;
  }

  return context.run(
    {
      requestId,
      requestedBy,
    },
    async () => {
      await next();
    }
  );
}
