"""Subscription status for logged-in users."""
from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.orm import Session

from core.auth import get_current_user
from db.models import User
from db.session import get_session
from routes.admin_users import get_settings_doc
from routes.auth import shape_user

router = APIRouter(prefix="/api/subscription", tags=["subscription"])


@router.get("/status")
def status(
    current: dict = Depends(get_current_user),
    db: Session = Depends(get_session),
):
    """Returns subscription + xtream info for the logged-in user."""
    user = db.scalar(select(User).where(User.id == current["id"]))
    shaped = shape_user(user.as_dict()) if user else {}
    settings = get_settings_doc(db)

    resolved_xtream = {"server": "", "username": "", "password": ""}
    if shaped.get("role") == "user":
        mode = shaped.get("xtream_mode", "shared")
        if mode == "own":
            resolved_xtream = {
                "server": shaped.get("xtream_server", ""),
                "username": shaped.get("xtream_username", ""),
                "password": shaped.get("xtream_password", ""),
            }
        else:
            resolved_xtream = {
                "server": settings.get("shared_xtream_server", ""),
                "username": settings.get("shared_xtream_username", ""),
                "password": settings.get("shared_xtream_password", ""),
            }

    if shaped.get("is_expired"):
        resolved_xtream = {"server": "", "username": "", "password": ""}

    return {
        "user": shaped,
        "xtream": resolved_xtream,
        "whatsapp_number": settings.get("whatsapp_number", ""),
    }
