// Gates content/community behind an active $10/mo membership.
// Status is kept in sync by Stripe webhooks; admins always pass.
import { queryOne } from '../db/client.js';
import { HttpError } from './error.js';

const ACTIVE_STATUSES = new Set(['active', 'trialing', 'past_due']);

export async function getSubscriptionStatus(userId) {
  const sub = await queryOne(
    `SELECT status, current_period_end FROM subscriptions WHERE user_id = ? ORDER BY updated_at DESC LIMIT 1`,
    [userId]
  );
  const status = sub ? sub.status : 'inactive';
  return {
    status,
    active: ACTIVE_STATUSES.has(status),
    current_period_end: sub ? sub.current_period_end : null,
  };
}

export function requireActiveSubscription() {
  return async (req, _res, next) => {
    try {
      if (!req.auth) throw new HttpError(401, 'unauthorized', 'Sign in required');
      if (req.auth.role === 'admin') return next();
      const { active } = await getSubscriptionStatus(req.auth.userId);
      if (!active) {
        throw new HttpError(402, 'subscription_required', 'An active membership is required to view this');
      }
      next();
    } catch (err) {
      next(err);
    }
  };
}
