'use strict';

const { createError } = require('../../utils/errorHandler');
const { verifyEngineeringKey, verifyEngineeringCredentials } = require('./engineeringKey');
const securityPermissions = require('../../middleware/permissions');

function cleanTenant(value) {
  return String(value || '')
    .trim()
    .replace(/[^a-zA-Z0-9._:-]/g, '_')
    .slice(0, 80);
}

function getTenantContext(req) {
  const tenantId = cleanTenant(
    req.user?.tenant_id ||
    req.user?.tenantId ||
    req.user?.cliente ||
    req.user?.client_id ||
    process.env.ARKHON_CLIENT_ID ||
    process.env.SUCURSAL_ID ||
    'local'
  );

  return {
    tenantId,
    user: req.user || null,
    branchId: cleanTenant(process.env.SUCURSAL_ID || 'principal'),
    branchName: process.env.SUCURSAL_NOMBRE || 'Sucursal principal',
  };
}

function hasPermission(req, permission) {
  return securityPermissions.hasPermission(req, permission);
}

function requirePermission(permission) {
  return (req, res, next) => {
    if (hasPermission(req, permission)) return next();
    return next(createError('No tienes permiso para acceder a este modulo de facturacion', 403));
  };
}

function requireEngineeringAccess(options = {}) {
  const allowLocalApi = options.allowLocalApi !== false;
  return (req, res, next) => {
    const esApiKeyLocal = req.user?.tipo === 'api_key' && req.user?.local === true;
    if (allowLocalApi && esApiKeyLocal) return next();

    const provided = req.headers['x-arkhon-engineering-key'];
    if (verifyEngineeringKey(provided)) return next();

    const email = req.headers['x-arkhon-engineering-email'] || req.body?.email;
    const password = req.headers['x-arkhon-engineering-password'] || req.body?.password;
    if (verifyEngineeringCredentials(email, password)) return next();

    loggerDenied(req);
    return next(createError('Configuracion tecnica restringida a Arkhon Engineering', 403));
  };
}

function loggerDenied(req) {
  try {
    const logger = require('../../utils/logger');
    logger.warn({ event: 'billing_engineering_denied', rol: req.user?.rol, tipo: req.user?.tipo, path: req.path, ip: req.ip });
  } catch (_) {}
}

module.exports = {
  getTenantContext,
  requirePermission,
  hasPermission,
  requireEngineeringAccess,
};
