"""Stripe billing service."""

import logging

logger = logging.getLogger(__name__)


async def update_user_tier(user_id: str, plan: str, status: str) -> None:
    """Update user's tier based on Stripe subscription status.

    Called by the webhook handler when subscription events occur.
    """
    from sqlalchemy import select

    from mixlift.db import async_session
    from mixlift.projects.models import User

    async with async_session() as session:
        result = await session.execute(select(User).where(User.id == user_id))
        user = result.scalar_one_or_none()
        if not user:
            logger.warning("update_user_tier: user not found id=%s", user_id)
            return

        if status in ("active", "trialing"):
            user.tier = plan
        elif status in ("canceled", "unpaid", "past_due", "incomplete_expired"):
            user.tier = "free"
        # "incomplete" — don't change tier, payment is still pending

        await session.commit()
        logger.info("User %s tier updated to %s (status=%s)", user_id, user.tier, status)
