// backend/src/middleware/auth.js
import jwt from 'jsonwebtoken';
import { query } from '../utils/db.js';

export async function requireAuth(req, res, next) {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    if (!token) return res.status(401).json({ error: 'No token provided' });

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const { rows } = await query(
      'SELECT id, email, role, status, plan_id, locale FROM users WHERE id = $1',
      [decoded.userId]
    );

    if (!rows[0]) return res.status(401).json({ error: 'User not found' });
    if (rows[0].status === 'banned') return res.status(403).json({ error: 'Account suspended' });

    req.user = rows[0];
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

export function requireActive(req, res, next) {
  const { status } = req.user;
  if (!['active', 'trial'].includes(status)) {
    return res.status(402).json({
      error: 'subscription_required',
      message: 'Active subscription required'
    });
  }
  next();
}

export function requirePlan(...planIds) {
  return (req, res, next) => {
    if (!planIds.includes(req.user.plan_id)) {
      return res.status(403).json({
        error: 'plan_upgrade_required',
        message: `This feature requires: ${planIds.join(' or ')} plan`,
        requiredPlans: planIds
      });
    }
    next();
  };
}

export function requireAdmin(req, res, next) {
  if (!['admin', 'superadmin'].includes(req.user.role)) {
    return res.status(403).json({ error: 'Admin access required' });
  }
  next();
}

export function requireSuperAdmin(req, res, next) {
  if (req.user.role !== 'superadmin') {
    return res.status(403).json({ error: 'Superadmin access required' });
  }
  next();
}
