const jwt = require('jsonwebtoken');
const { User, CompanyUser } = require('../models');

// ─── JWT Auth Middleware ───────────────────────────────────────────────────────
const authMiddleware = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ success: false, message: 'No token provided' });
    }
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findByPk(decoded.id, {
      attributes: ['id', 'name', 'email', 'avatar_url', 'is_active'],
    });
    if (!user || !user.is_active) {
      return res.status(401).json({ success: false, message: 'Invalid or inactive user' });
    }
    req.user = user;
    next();
  } catch (err) {
    return res.status(401).json({ success: false, message: 'Token invalid or expired' });
  }
};

// ─── Company Context Middleware ───────────────────────────────────────────────
const companyContext = async (req, res, next) => {
  try {
    const companyId = req.headers['x-company-id'] || req.query.company_id;
    if (!companyId) {
      return res.status(400).json({ success: false, message: 'Company ID required' });
    }
    const membership = await CompanyUser.findOne({
      where: { company_id: companyId, user_id: req.user.id, is_active: true },
    });
    if (!membership) {
      return res.status(403).json({ success: false, message: 'Access denied to this company' });
    }
    req.companyId = companyId;
    req.userRole = membership.role;
    next();
  } catch (err) {
    next(err);
  }
};

// ─── RBAC Middleware ──────────────────────────────────────────────────────────
const ROLE_HIERARCHY = { owner: 4, admin: 3, accountant: 2, viewer: 1 };

const rbac = (requiredRole) => (req, res, next) => {
  const userLevel = ROLE_HIERARCHY[req.userRole] || 0;
  const requiredLevel = ROLE_HIERARCHY[requiredRole] || 0;
  if (userLevel < requiredLevel) {
    return res.status(403).json({
      success: false,
      message: `Requires ${requiredRole} role or higher`,
    });
  }
  next();
};

// ─── Error Handler ────────────────────────────────────────────────────────────
const errorHandler = (err, req, res, next) => {
  console.error(err.stack);
  if (err.name === 'SequelizeValidationError') {
    return res.status(400).json({
      success: false,
      message: 'Validation error',
      errors: err.errors.map((e) => ({ field: e.path, message: e.message })),
    });
  }
  if (err.name === 'SequelizeUniqueConstraintError') {
    return res.status(409).json({ success: false, message: 'Duplicate entry' });
  }
  res.status(err.status || 500).json({
    success: false,
    message: err.message || 'Internal server error',
  });
};

module.exports = { authMiddleware, companyContext, rbac, errorHandler };
