import type { NextFunction, Request, Response } from 'express';
import ScopeService from '@/services/scope';

const LEVEL_HEADER = 'x-active-tenant-level';
const ID_HEADER = 'x-active-tenant-id';

function headerValue(req: Request, name: string): string | null {
  const raw = req.headers[name];
  if (Array.isArray(raw)) return raw[0] ?? null;
  return typeof raw === 'string' && raw.length > 0 ? raw : null;
}

/**
 * Drill-down support: if the request carries an active-tenant header
 * (`x-active-tenant-level` + `x-active-tenant-id`), validate it against the
 * authenticated user's scope and attach the resolved tenant chain to
 * `req.currentUser.activeScope`. Downstream scope resolution then acts as that
 * tenant. No header → no override (the user's own scope applies). Invalid /
 * out-of-scope targets are rejected (403).
 */
export async function resolveActiveScope(
  req: Request,
  _res: Response,
  next: NextFunction,
): Promise<void> {
  try {
    const currentUser = req.currentUser;
    const level = headerValue(req, LEVEL_HEADER);
    const id = headerValue(req, ID_HEADER);

    if (currentUser && level && id) {
      const activeScope = await ScopeService.resolveActiveScope(
        level,
        id,
        currentUser,
      );
      req.currentUser = { ...currentUser, activeScope };
    }
    next();
  } catch (error) {
    next(error);
  }
}
