const { AlphaInvitation } = require("../models");
const logger = require("../utils/logger");

/**
 * Middleware to require alpha access for protected routes
 * Checks for valid alpha cookie or registered user with invitation
 */
const requireAlphaAccess = async (req, res, next) => {
  try {
    // Bypass alpha access check if feature is disabled
    if (process.env.ALPHA_TESTING_ENABLED !== 'true') {
      return next();
    }

    let hasAccess = false;

    // Check 1: Valid alpha access cookie
    if (req.cookies && req.cookies.alphaAccessCode) {
      const { code } = req.cookies.alphaAccessCode;
      if (code) {
        const invitation = await AlphaInvitation.findOne({
          where: { code, status: ["pending", "active"] },
        });
        if (invitation) {
          hasAccess = true;
        }
      }
    }

    // Check 2: Authenticated user who has used an invitation
    if (!hasAccess && req.user && req.user.id) {
      const invitation = await AlphaInvitation.findOne({
        where: { usedBy: req.user.id },
      });
      if (invitation) {
        hasAccess = true;
      }
    }

    if (!hasAccess) {
      logger.warn(
        `Alpha access denied for request to ${req.path}`,
        {
          ip: req.ip,
          userId: req.user?.id,
        }
      );
      return res.status(403).json({
        error: "Alpha access required",
        code: "ALPHA_ACCESS_REQUIRED",
      });
    }

    // Access granted
    next();
  } catch (error) {
    logger.error(`Error checking alpha access: ${error.message}`, { error });
    res.status(500).json({
      error: "Server error",
    });
  }
};

module.exports = { requireAlphaAccess };
