"""Access control helpers for marketplace purchases."""
from app.models.features import MarketplaceListing, MarketplacePurchase


def has_report_access(user, report):
    """Check if user has access to a report (owner, admin, completed marketplace purchase or free listing)."""
    if not user or not report:
        return False
    # Admins have access to all reports
    if user.is_admin:
        return True
    # Owner always has access
    if report.user_id == user.id:
        return True
    # Check for completed marketplace purchase
    listing = MarketplaceListing.query.filter_by(report_id=report.id, is_active=True).first()
    if not listing:
        return False
    # Free listings are accessible to all authenticated users
    if listing.listing_goal == "free" and listing.approval_status == "approved":
        return True
    # Check for completed purchase
    purchase = MarketplacePurchase.query.filter_by(
        listing_id=listing.id, buyer_id=user.id, status="completed"
    ).first()
    return purchase is not None


def is_report_owner(user, report):
    """Check if user is the original owner of the report."""
    if not user or not report:
        return False
    return report.user_id == user.id
