"""
Current-user dependency for JWT-protected endpoints.

Use `current_user: User = Depends(get_current_user)` on any endpoint
that should only be accessible to a logged-in customer (dashboard,
crop plans, notifications). This is distinct from `verify_api_key` in
app/core/security.py, which protects the machine-to-machine API surface.
"""

from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.auth_tokens import decode_token
from app.core.exceptions import AuthenticationError
from app.db.models import User
from app.db.session import get_db_session

bearer_scheme = HTTPBearer(auto_error=False)


async def get_current_user(
    credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
    db: AsyncSession = Depends(get_db_session),
) -> User:
    if credentials is None:
        raise AuthenticationError(message="Authentication required. Please log in.")

    payload = decode_token(credentials.credentials, expected_type="access")
    user_id = payload.get("sub")
    if not user_id:
        raise AuthenticationError(message="Invalid token payload")

    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if user is None:
        raise AuthenticationError(message="User account no longer exists")
    if not user.is_active:
        raise AuthenticationError(message="This account has been deactivated. Contact support.")

    return user
