const householdModel = require("../models/household.model");
const { sendError } = require("../utils/http");
const { logError } = require("../utils/logger");

// Middleware to check if user belongs to household
exports.householdAccess = async (req, res, next) => {
  try {
    const householdId = parseInt(req.params.householdId || req.params.hId);
    const userId = req.user.id;

    if (!householdId) {
      return sendError(res, 400, "Household ID required");
    }

    // Check if user is member of household
    const isMember = await householdModel.isHouseholdMember(householdId, userId);

    if (!isMember) {
      return sendError(res, 403, "Access denied. You are not a member of this household.");
    }

    // Get user's role in household
    const role = await householdModel.getUserRole(householdId, userId);

    // Attach household info to request
    req.household = {
      id: householdId,
      role: role
    };

    next();
  } catch (error) {
    logError(req, "middleware.householdAccess", error);
    sendError(res, 500, "Server error checking household access");
  }
};

// Middleware to require specific household role(s)
exports.requireHouseholdRole = (...allowedRoles) => {
  return (req, res, next) => {
    if (!req.household) {
      return sendError(res, 500, "Household context not set. Use householdAccess middleware first.");
    }

    if (!allowedRoles.includes(req.household.role)) {
      return sendError(
        res,
        403,
        `Access denied. Required role: ${allowedRoles.join(" or ")}. Your role: ${req.household.role}`
      );
    }

    next();
  };
};

// Middleware to require admin/owner role in household
exports.requireHouseholdAdmin = exports.requireHouseholdRole('owner', 'admin');

// Middleware to check store access (household must have store)
exports.storeAccess = async (req, res, next) => {
  try {
    const storeId = parseInt(req.params.storeId || req.params.sId);

    if (!storeId) {
      return sendError(res, 400, "Store ID required");
    }

    if (!req.household) {
      return sendError(res, 500, "Household context not set. Use householdAccess middleware first.");
    }

    // Check if household has access to this store
    const storeModel = require("../models/store.model");
    const hasStore = await storeModel.householdHasStore(req.household.id, storeId);

    if (!hasStore) {
      return sendError(res, 403, "This household does not have access to this store.");
    }

    // Attach store info to request
    req.store = {
      id: storeId
    };

    next();
  } catch (error) {
    logError(req, "middleware.storeAccess", error);
    sendError(res, 500, "Server error checking store access");
  }
};

// Middleware to require system admin role
exports.requireSystemAdmin = (req, res, next) => {
  if (!req.user) {
    return sendError(res, 401, "Authentication required");
  }

  if (req.user.role !== 'system_admin') {
    return sendError(res, 403, "Access denied. System administrator privileges required.");
  }

  next();
};
