const { ClubSubscription, SubscriptionPlan, ClubFeature, Feature } = require('../models');
const { Op } = require('sequelize');

/**
 * 클럽이 특정 featureCode를 사용할 수 있는지 여부 반환
 * @param {number} clubId
 * @param {string} featureCode
 * @returns {Promise<boolean>}
 */
async function clubHasFeature(clubId, featureCode) {
  // 활성 구독 플랜에서 해당 기능이 포함되어 있는지 체크
  const clubSub = await ClubSubscription.findOne({
    where: { clubId, status: 'active', endDate: { [Op.gt]: new Date() } },
    include: [{
      model: SubscriptionPlan,
      include: [{
        model: Feature,
        where: { code: featureCode, status: 'active' },
        through: { where: { status: 'active' } }
      }]
    }]
  });
  if (clubSub) return true;

  // 별도 활성화된 ClubFeature가 있는지 체크
  const clubFeature = await ClubFeature.findOne({
    where: {
      clubId,
      enabled: true,
      expiryDate: { [Op.or]: [null, { [Op.gt]: new Date() }] }
    },
    include: [{
      model: Feature,
      where: { code: featureCode, status: 'active' }
    }]
  });
  return !!clubFeature;
}

module.exports = { clubHasFeature };
