package de.oaa.xxx.subscription;

import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Optional;
import java.util.UUID;

/**
 * Central service for subscription-based feature limits.
 * All limit constants are defined here – add new resource types as needed.
 */
@Service
public class SubscriptionLimitService {

    // ── Limits for STANDARD (no active subscription) ──
    public static final int STANDARD_MAX_LOCK_TEMPLATES    = 6;
    public static final int STANDARD_MAX_TASK_GROUPS       = 6;
    public static final int STANDARD_MAX_TASKS_PER_GROUP   = 50;
    public static final int STANDARD_MAX_TOYS              = 10;
    public static final int STANDARD_MAX_KEYHOLDER_OFFERS  = 5;

    private final UserSubscriptionRepository subscriptionRepository;

    public SubscriptionLimitService(UserSubscriptionRepository subscriptionRepository) {
        this.subscriptionRepository = subscriptionRepository;
    }

    /** Returns the active subscription for the user, or empty if none. */
    public Optional<UserSubscriptionEntity> getActiveSubscription(UUID userId) {
        return subscriptionRepository
                .findTopByUserIdAndValidUntilGreaterThanEqualOrderByValidUntilDesc(userId, LocalDate.now());
    }

    /** True if the user has an active (non-STANDARD) subscription. */
    public boolean hasActivePaidSubscription(UUID userId) {
        return getActiveSubscription(userId)
                .filter(s -> s.getSubscriptionType() != SubscriptionType.STANDARD)
                .isPresent();
    }

    /** Max total lock templates (cardlock + timelock combined) allowed for this user. */
    public int maxLockTemplates(UUID userId) {
        if (hasActivePaidSubscription(userId)) return Integer.MAX_VALUE;
        return STANDARD_MAX_LOCK_TEMPLATES;
    }

    /** Max task groups the user may own. */
    public int maxTaskGroups(UUID userId) {
        if (hasActivePaidSubscription(userId)) return Integer.MAX_VALUE;
        return STANDARD_MAX_TASK_GROUPS;
    }

    /** Max tasks per task group. */
    public int maxTasksPerGroup(UUID userId) {
        if (hasActivePaidSubscription(userId)) return Integer.MAX_VALUE;
        return STANDARD_MAX_TASKS_PER_GROUP;
    }

    /** Max individual toys the user may create. */
    public int maxToys(UUID userId) {
        if (hasActivePaidSubscription(userId)) return Integer.MAX_VALUE;
        return STANDARD_MAX_TOYS;
    }

    /** Max keyholder offers the user may create. */
    public int maxKeyholderOffers(UUID userId) {
        if (hasActivePaidSubscription(userId)) return Integer.MAX_VALUE;
        return STANDARD_MAX_KEYHOLDER_OFFERS;
    }
}
