# core/utils.py
"""
Utility helpers for SwiftPOS multi-tenant SaaS.

All limit/feature checks now use request.company.plan (the new Company-based system).
The old SystemSettings / License / SubscriptionPlan references are removed.
"""
from django.core.exceptions import PermissionDenied
from django.utils import timezone


# ─────────────────────────────────────────────────────────────
# Plan / Company Helpers
# ─────────────────────────────────────────────────────────────

def get_company_plan(request):
    """
    Returns the Plan for request.company, or None.
    Safe to call even if request.company is None.
    """
    company = getattr(request, 'company', None)
    return getattr(company, 'plan', None)


def check_limit_or_block(limit_name: str, request=None, company=None):
    """
    Enforce per-company plan limits.

    limit_name can be:
      - "products"
      - "categories"
      - "orders_per_day"
      - "customers"
      - "staff"
      - "branches"

    Pass either request (preferred) or company directly.
    Raises PermissionDenied if limit exceeded or company inactive.
    """
    from inventory.models import Product, ProductCategory
    from sales.models import POSOrder, Customer

    # Resolve company
    if company is None and request is not None:
        company = getattr(request, 'company', None)
        if company is None and request.user.is_authenticated:
            company = getattr(request.user, 'company', None)

    if not company or not company.is_accessible:
        raise PermissionDenied(
            "Your account is inactive or subscription has expired. "
            "Please contact support."
        )

    plan = company.plan
    if not plan:
        # No plan assigned → unlimited (for development / setup phase)
        return

    today = timezone.now().date()

    # Map limit → (max_allowed, current_count)
    if limit_name == "products":
        max_allowed = plan.max_products
        current = Product.objects.filter(company=company).count()
    elif limit_name == "categories":
        max_allowed = plan.max_categories
        current = ProductCategory.objects.filter(company=company).count()
    elif limit_name == "orders_per_day":
        max_allowed = plan.max_orders_per_day
        current = POSOrder.objects.filter(company=company, created_at__date=today).count()
    elif limit_name == "customers":
        max_allowed = plan.max_customers
        current = Customer.objects.filter(company=company).count()
    elif limit_name == "staff":
        from accounts.models import CustomUser
        max_allowed = plan.max_staff
        current = CustomUser.objects.filter(company=company).count()
    elif limit_name == "branches":
        from core.models import Branch
        max_allowed = plan.max_branches
        current = Branch.objects.filter(company=company).count()
    else:
        return  # Unknown limit → allow

    # 0 means unlimited
    if max_allowed and current >= max_allowed:
        raise PermissionDenied(
            "You have reached the limit of your current subscription plan. "
            "Please contact support to upgrade."
        )


def is_feature_enabled(feature_name: str, request=None, company=None) -> bool:
    """
    Check if a feature is enabled on the company's plan.

    Accepts the new Plan field names (feature_*) or old aliases for backward compat.
    """
    if company is None and request is not None:
        company = getattr(request, 'company', None)

    plan = getattr(company, 'plan', None)
    if not plan:
        return False

    # New Plan model attribute mapping
    FEATURE_MAP = {
        'multi_branch':       'feature_multi_branch',
        'credit_sales':       'feature_credit_sales',
        'advanced_reports':   'feature_advanced_reports',
        'barcode_scanner':    'feature_barcode_pos',
        'grid_pos':           'feature_pos_terminal_v2_grid',
        'bulk_import':        'feature_bulk_import',
        'export':             'feature_export',
        'profit_loss':        'feature_profit_loss',
        'audit_logs':         'feature_audit_logs',
        'suspicious_activity':'feature_suspicious_activity',
        'wholesale_price':    'feature_wholesale_price',
        'discount':           'feature_discount',
        'promo':              'feature_promo',
        'android_app':        'feature_android_app',
    }

    attr = FEATURE_MAP.get(feature_name, f'feature_{feature_name}')
    return bool(getattr(plan, attr, False))


# ─────────────────────────────────────────────────────────────
# Branch Filtering (kept for backward compat, now company-aware)
# ─────────────────────────────────────────────────────────────

def filter_orders_by_user_branch(request, queryset):
    """
    Strict branch filtering within a company:
    - Superadmin / Admin → sees all (already company-filtered upstream)
    - Manager / Cashier  → only their assigned branch
    """
    user = request.user

    if user.role in ('superadmin', 'admin'):
        return queryset

    if user.branch:
        return queryset.filter(branch=user.branch)

    return queryset.none()
