import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { randomUUID } from 'crypto';
import { RequestContext, requestContextStorage } from './request-context';

/**
 * Creates the per-request context store before any guard runs. Guards then
 * fill in identity fields on the same object once the caller is authenticated.
 */
@Injectable()
export class RequestContextMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    const requestId = (req.headers['x-request-id'] as string | undefined) ?? randomUUID();
    res.setHeader('x-request-id', requestId);
    const ctx: RequestContext = {
      requestId,
      tenantId: null,
      actorType: 'USER',
      actorId: null,
      actorName: null,
      userId: null,
      storerId: null,
      permissions: [],
      warehouseIds: [],
      features: [],
      ip: req.ip,
      userAgent: req.headers['user-agent'],
      deviceId: req.headers['x-device-id'] as string | undefined,
      bypassRls: false,
    };
    requestContextStorage.run(ctx, () => next());
  }
}
