from datetime import timedelta

import jwt
import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session

from app.api.v1.deps import get_current_user
from app.core import security
from app.core.config import settings
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.otp import OTPPurpose
from app.models.user import User, UserRole
from app.schemas.auth import (
    AddEmailStartRequest,
    AddPhoneStartRequest,
    ChangePinRequest,
    CustomerSignupRequest,
    EmailOtpVerifyRequest,
    ForgotPinStartRequest,
    GoogleConnectRequest,
    GoogleSignInRequest,
    LoginRequest,
    LogoutRequest,
    MarketingConsentRequest,
    MessageResponse,
    OtpVerifyRequest,
    PhoneOtpVerifyRequest,
    PinSetRequest,
    RefreshRequest,
    TokenResponse,
    UserOut,
    VerificationTokenOnlyRequest,
    VerificationTokenResponse,
)
from app.services import google_oauth as google_oauth_service
from app.services import otp as otp_service
from app.services import token_blacklist
from app.services import tokens as token_service
from app.services.email import send_templated_email
from app.services.google_oauth import GoogleTokenError
from app.services.otp import OTPError
from app.services.rate_limit import rate_limit_by_ip_and_phone
from app.services.tokens import RefreshTokenError
from app.utils.time import utcnow

router = APIRouter(prefix="/auth", tags=["auth"])

_INCORRECT_LOGIN = HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED,
    detail="Incorrect phone number, email, or PIN.",
)
_ACCOUNT_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this phone number already exists.",
)
_EMAIL_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this email already exists.",
)


def _issue_tokens(db: Session, user: User) -> TokenResponse:
    access_token = security.create_access_token(user.id, user.role)
    refresh_token = token_service.issue_refresh_token(db, user)
    return TokenResponse(
        access_token=access_token,
        refresh_token=refresh_token,
        user=UserOut.model_validate(user),
    )


def _message_with_debug_otp(message: str, code: str | None) -> MessageResponse:
    if code is not None and settings.environment == "development":
        return MessageResponse(message=message, debug_otp=code)
    return MessageResponse(message=message)


def _send_welcome_email_if_possible(user: User) -> None:
    """Fires once, right after a brand-new customer account is
    created — signup_complete (phone or email verified) and
    google_signin's new-account branch, never on an existing user
    logging back in. A no-op for a phone-only signup with no email on
    file — there's nowhere to send it."""
    if user.email:
        send_templated_email(
            user.email,
            "Welcome to YENEB CODS",
            "welcome",
            {"name": user.name, "app_download_url": settings.app_download_url},
        )


def _verified_phone_owner(db: Session, phone: str) -> User | None:
    return (
        db.query(User)
        .filter(User.phone == phone, User.is_phone_verified.is_(True))
        .first()
    )


def _verified_email_owner(db: Session, email: str) -> User | None:
    return (
        db.query(User)
        .filter(User.email == email, User.is_email_verified.is_(True))
        .first()
    )


@router.post("/signup/start", response_model=MessageResponse)
def signup_start(
    payload: CustomerSignupRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MessageResponse:
    """Step 1 of customer signup: name + exactly one of phone or email
    (see CustomerSignupRequest) — phone-first or email-first, the
    customer's choice. Sends a single code to whichever one was given;
    the other identifier isn't collected at all here and can be added
    later, skippably, via /auth/phone/* or /auth/email/*.

    Only customers self-signup — courier, supplier, and admin accounts
    are invited by an admin, see app.api.v1.endpoints.admin.
    """
    identifier = payload.phone or payload.email
    channel = "sms" if payload.phone else "email"
    rate_limit_by_ip_and_phone(redis, request, identifier, "signup_start")
    if payload.phone and _verified_phone_owner(db, payload.phone) is not None:
        raise _ACCOUNT_EXISTS
    if payload.email and _verified_email_owner(db, payload.email) is not None:
        raise _EMAIL_EXISTS

    code = otp_service.create_and_send_otp(
        db, identifier, OTPPurpose.SIGNUP, channel=channel, pending_name=payload.name
    )
    message = (
        f"Verification code sent. It expires in {settings.otp_expire_minutes} minutes."
    )
    return _message_with_debug_otp(message, code)


@router.post("/signup/verify-otp", response_model=VerificationTokenResponse)
def signup_verify_otp(
    payload: OtpVerifyRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> VerificationTokenResponse:
    """Step 2 of customer signup: verify the code sent to whichever
    identifier was submitted in /signup/start.

    Returns a short-lived verification_token to use in the next step —
    the code itself isn't needed again.
    """
    rate_limit_by_ip_and_phone(redis, request, payload.identifier, "signup_verify_otp")
    try:
        _, token = otp_service.verify_otp(
            db, payload.identifier, OTPPurpose.SIGNUP, payload.otp_code
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    return VerificationTokenResponse(
        verification_token=token,
        expires_in_minutes=settings.verification_token_expire_minutes,
    )


@router.post("/signup/complete", response_model=TokenResponse)
def signup_complete(
    payload: PinSetRequest, db: Session = Depends(get_db)
) -> TokenResponse:
    """Step 3 of customer signup: set a PIN using the verification_token
    from /signup/verify-otp. Creates the account and logs the customer
    in immediately. Only the identifier that was actually verified
    (verified.channel — "sms" or "email") is set on the new account;
    the other stays fully unset, since single-identifier signup never
    collected it (see CustomerSignupRequest)."""
    try:
        verified = otp_service.consume_verification_token(
            db, OTPPurpose.SIGNUP, payload.verification_token
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    is_phone = verified.channel == "sms"

    if is_phone and _verified_phone_owner(db, verified.identifier) is not None:
        raise _ACCOUNT_EXISTS
    if not is_phone and _verified_email_owner(db, verified.identifier) is not None:
        raise _EMAIL_EXISTS

    user = User(
        phone=verified.identifier if is_phone else None,
        name=verified.pending_name or "",
        email=verified.identifier if not is_phone else None,
        role=UserRole.CUSTOMER.value,
        pin_hash=security.hash_pin(payload.pin),
        is_phone_verified=is_phone,
        is_email_verified=not is_phone,
    )
    db.add(user)
    db.commit()
    db.refresh(user)
    _send_welcome_email_if_possible(user)

    return _issue_tokens(db, user)


@router.post("/google", response_model=TokenResponse)
def google_signin(
    payload: GoogleSignInRequest, db: Session = Depends(get_db)
) -> TokenResponse:
    """Sign up or log in with Google. Only ever touches an account
    already linked to this exact Google identity (google_sub), or
    creates a brand-new one — it never auto-links to an existing
    phone/email account on an email match, even though Google has
    verified that email, because Google proving *this* person owns
    that email doesn't prove they're the same person who created the
    other account. See POST /auth/google/connect for the deliberate,
    PIN-confirmed way to link instead.

    No phone, no PIN for a newly-created account: it authenticates by
    presenting a fresh Google ID token each time (see the User model
    docstring for how that's told apart from an invited-but-not-yet-
    activated account, which also has pin_hash=None)."""
    try:
        account = google_oauth_service.verify_google_id_token(payload.id_token)
    except GoogleTokenError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc)
        ) from exc

    user = db.query(User).filter(User.google_sub == account.sub).first()
    if user is None:
        existing = db.query(User).filter(User.email == account.email).first()
        if existing is not None:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail=(
                    "An account with this email already exists. Log in, then "
                    "connect Google from your account."
                ),
            )
        user = User(
            phone=None,
            name=account.name or account.email.split("@")[0],
            email=account.email,
            role=UserRole.CUSTOMER.value,
            pin_hash=None,
            google_sub=account.sub,
            is_phone_verified=False,
            # Google already verified this — see
            # google_oauth.verify_google_id_token's email_verified check.
            is_email_verified=True,
        )
        db.add(user)
        db.commit()
        db.refresh(user)
        _send_welcome_email_if_possible(user)

    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This account has been disabled.",
        )

    return _issue_tokens(db, user)


@router.post("/google/connect", response_model=TokenResponse)
def google_connect(
    payload: GoogleConnectRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> TokenResponse:
    """Deliberately links a Google identity to the logged-in account —
    what an app prompts the user through after google_signin() returns
    409 for an email collision. Requires re-entering the PIN even
    though the caller is already authenticated, as proof this specific
    sensitive action is really the account holder (see
    GoogleConnectRequest)."""
    if current_user.pin_hash is None or not security.verify_pin(
        payload.pin, current_user.pin_hash
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect PIN."
        )

    try:
        account = google_oauth_service.verify_google_id_token(payload.id_token)
    except GoogleTokenError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc)
        ) from exc

    conflict = (
        db.query(User)
        .filter(User.google_sub == account.sub, User.id != current_user.id)
        .first()
    )
    if conflict is not None:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This Google account is already linked to a different account.",
        )

    current_user.google_sub = account.sub
    if account.email == current_user.email and not current_user.is_email_verified:
        # Google independently proved this specific email belongs to
        # whoever's connecting it — safe to promote, unlike the
        # auto-link case, since we already know (via PIN, above) this
        # is the existing account's own owner doing it.
        if _verified_email_owner(db, current_user.email) is None:
            current_user.is_email_verified = True
    db.commit()
    db.refresh(current_user)

    return _issue_tokens(db, current_user)


@router.post("/login", response_model=TokenResponse)
def login(
    payload: LoginRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> TokenResponse:
    """identifier is a phone number or an email address (see
    LoginRequest) — only a *verified* one is ever matched, since an
    unverified value on the account was never proven to belong to its
    holder."""
    rate_limit_by_ip_and_phone(redis, request, payload.identifier, "login")
    if "@" in payload.identifier:
        user = _verified_email_owner(db, payload.identifier)
    else:
        user = _verified_phone_owner(db, payload.identifier)
    if user is None:
        # Not a verified match — but if this identifier belongs to an
        # invited-but-not-yet-activated account, surface that
        # specifically instead of a generic incorrect-login error.
        # Safe to look up by an unverified value here: unlike
        # self-signup (which always sets pin_hash immediately, so
        # never matches pin_hash IS NULL), an invited row is uniquely
        # reserved by app.api.v1.endpoints.admin at invite time
        # regardless of is_phone_verified — there's no squatting risk
        # to guard against for this specific case. google_sub IS NULL
        # excludes Google accounts, which also have pin_hash=None but
        # aren't "pending activation" — they just don't use PIN login.
        pending = (
            db.query(User)
            .filter(
                (User.phone == payload.identifier) | (User.email == payload.identifier),
                User.pin_hash.is_(None),
                User.google_sub.is_(None),
            )
            .first()
        )
        if pending is not None:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Activate your account first — check your SMS for a verification code.",
            )
        raise _INCORRECT_LOGIN

    if user.pin_hash is None:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Activate your account first — check your SMS for a verification code.",
        )

    if user.locked_until is not None and user.locked_until > utcnow():
        raise HTTPException(
            status_code=status.HTTP_423_LOCKED,
            detail="Too many failed attempts. Try again in a few minutes, or reset your PIN.",
        )

    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This account has been disabled.",
        )

    if not security.verify_pin(payload.pin, user.pin_hash):
        user.failed_pin_attempts += 1
        if user.failed_pin_attempts >= settings.max_pin_attempts:
            user.locked_until = utcnow() + timedelta(minutes=settings.lockout_minutes)
        db.commit()
        raise _INCORRECT_LOGIN

    user.failed_pin_attempts = 0
    user.locked_until = None
    db.commit()

    return _issue_tokens(db, user)


@router.post("/refresh", response_model=TokenResponse)
def refresh(
    payload: RefreshRequest,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> TokenResponse:
    """Trade a refresh token for a new access token. The refresh token
    is rotated: the one submitted here stops working, and a new one is
    returned to use next time."""
    try:
        user, new_refresh_token = token_service.rotate_refresh_token(
            db, redis, payload.refresh_token
        )
    except RefreshTokenError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc)
        ) from exc

    access_token = security.create_access_token(user.id, user.role)
    return TokenResponse(
        access_token=access_token,
        refresh_token=new_refresh_token,
        user=UserOut.model_validate(user),
    )


# Optional — unlike bearer_scheme (app.api.v1.deps), a missing/invalid
# header here just means "nothing to blacklist," not a 401. Logout has
# never required a valid access token (only the refresh token, in the
# body) and shouldn't start now — this only adds best-effort
# blacklisting of that token *when the caller happens to send one*.
_optional_bearer_scheme = HTTPBearer(auto_error=False)


@router.post("/logout", response_model=MessageResponse)
def logout(
    payload: LogoutRequest,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
    credentials: HTTPAuthorizationCredentials | None = Depends(_optional_bearer_scheme),
) -> MessageResponse:
    token_service.revoke_refresh_token(db, payload.refresh_token)
    if credentials is not None:
        try:
            claims = security.decode_access_token(credentials.credentials)
            token_blacklist.blacklist_access_token(
                redis, credentials.credentials, int(claims["exp"])
            )
        except (jwt.PyJWTError, KeyError, ValueError):
            # Already expired/malformed — nothing worth blacklisting,
            # and the refresh-token revocation above already happened.
            pass
    return MessageResponse(message="Logged out.")


@router.post("/forgot-pin/start", response_model=MessageResponse)
def forgot_pin_start(
    payload: ForgotPinStartRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MessageResponse:
    """identifier is a phone number or an email address — an
    email-only-signup customer has no phone to reset a PIN by SMS
    with, so this supports either (see ForgotPinStartRequest)."""
    rate_limit_by_ip_and_phone(redis, request, payload.identifier, "forgot_pin_start")
    is_email = "@" in payload.identifier
    user = (
        _verified_email_owner(db, payload.identifier)
        if is_email
        else _verified_phone_owner(db, payload.identifier)
    )
    message = "If that account is registered, a verification code has been sent."

    # Same response whether or not the account is registered, so this
    # endpoint can't be used to check which numbers/emails have
    # accounts.
    if user is None:
        return MessageResponse(message=message)

    code = otp_service.create_and_send_otp(
        db,
        payload.identifier,
        OTPPurpose.RESET_PIN,
        channel="email" if is_email else "sms",
    )
    return _message_with_debug_otp(message, code)


@router.post("/forgot-pin/verify-otp", response_model=VerificationTokenResponse)
def forgot_pin_verify_otp(
    payload: OtpVerifyRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> VerificationTokenResponse:
    rate_limit_by_ip_and_phone(
        redis, request, payload.identifier, "forgot_pin_verify_otp"
    )
    try:
        _, token = otp_service.verify_otp(
            db, payload.identifier, OTPPurpose.RESET_PIN, payload.otp_code
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    return VerificationTokenResponse(
        verification_token=token,
        expires_in_minutes=settings.verification_token_expire_minutes,
    )


@router.post("/forgot-pin/reset", response_model=MessageResponse)
def forgot_pin_reset(
    payload: PinSetRequest, db: Session = Depends(get_db)
) -> MessageResponse:
    try:
        verified = otp_service.consume_verification_token(
            db, OTPPurpose.RESET_PIN, payload.verification_token
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    is_email = verified.channel == "email"
    user = (
        _verified_email_owner(db, verified.identifier)
        if is_email
        else _verified_phone_owner(db, verified.identifier)
    )
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Verify your phone number or email again.",
        )

    user.pin_hash = security.hash_pin(payload.pin)
    user.failed_pin_attempts = 0
    user.locked_until = None
    db.commit()

    return MessageResponse(message="Your PIN has been reset. Log in with your new PIN.")


@router.post("/activate/verify-otp", response_model=VerificationTokenResponse)
def activate_verify_otp(
    payload: PhoneOtpVerifyRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> VerificationTokenResponse:
    """First step for a courier/supplier/admin account created by an
    admin invite: verify the SMS code sent at invite time."""
    rate_limit_by_ip_and_phone(redis, request, payload.phone, "activate_verify_otp")
    try:
        _, token = otp_service.verify_otp(
            db, payload.phone, OTPPurpose.ACTIVATE_ACCOUNT, payload.otp_code
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    return VerificationTokenResponse(
        verification_token=token,
        expires_in_minutes=settings.verification_token_expire_minutes,
    )


@router.post("/activate/complete", response_model=TokenResponse)
def activate_complete(
    payload: PinSetRequest, db: Session = Depends(get_db)
) -> TokenResponse:
    """Second step: set a PIN on the invited account and log in.

    Unlike /signup/complete, the account already exists (an admin
    created it) — this just sets its PIN for the first time. This is
    also the moment its phone actually becomes verified — admin.py's
    invite flow reserves the phone immediately (it isn't the
    self-service squatting risk the dual-OTP signup path guards
    against — a trusted admin typed it, not an arbitrary end user),
    but the account itself doesn't get the trust benefits of
    is_phone_verified (login, uniqueness) until this OTP is actually
    completed.
    """
    try:
        verified = otp_service.consume_verification_token(
            db, OTPPurpose.ACTIVATE_ACCOUNT, payload.verification_token
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    user = db.query(User).filter(User.phone == verified.identifier).first()
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Account not found. Ask an admin to invite you again.",
        )
    if user.pin_hash is not None:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This account has already been activated. Log in instead.",
        )

    user.pin_hash = security.hash_pin(payload.pin)
    user.is_phone_verified = True
    db.commit()
    db.refresh(user)

    return _issue_tokens(db, user)


@router.post("/phone/start", response_model=MessageResponse)
def add_phone_start(
    payload: AddPhoneStartRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
    current_user: User = Depends(get_current_user),
) -> MessageResponse:
    """First step of adding/replacing a verified phone number on the
    logged-in account — e.g. so a Google Sign-In customer can later
    pay via Telebirr, which needs a real Ethiopian phone. Any
    authenticated account can use this, not just Google ones."""
    rate_limit_by_ip_and_phone(redis, request, payload.phone, "add_phone_start")
    existing = _verified_phone_owner(db, payload.phone)
    if existing is not None and existing.id != current_user.id:
        raise _ACCOUNT_EXISTS

    code = otp_service.create_and_send_otp(db, payload.phone, OTPPurpose.ADD_PHONE)
    return _message_with_debug_otp(
        f"Verification code sent. It expires in {settings.otp_expire_minutes} minutes.",
        code,
    )


@router.post("/phone/verify-otp", response_model=VerificationTokenResponse)
def add_phone_verify_otp(
    payload: PhoneOtpVerifyRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
    _current_user: User = Depends(get_current_user),
) -> VerificationTokenResponse:
    rate_limit_by_ip_and_phone(redis, request, payload.phone, "add_phone_verify_otp")
    try:
        _, token = otp_service.verify_otp(
            db, payload.phone, OTPPurpose.ADD_PHONE, payload.otp_code
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    return VerificationTokenResponse(
        verification_token=token,
        expires_in_minutes=settings.verification_token_expire_minutes,
    )


@router.post("/phone/complete", response_model=UserOut)
def add_phone_complete(
    payload: VerificationTokenOnlyRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> UserOut:
    """Final step: attaches the now-verified phone to the logged-in
    account. Re-checks uniqueness (among verified phones only) in case
    someone else claimed and verified the same number between /start
    and here."""
    try:
        verified = otp_service.consume_verification_token(
            db, OTPPurpose.ADD_PHONE, payload.verification_token
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    existing = _verified_phone_owner(db, verified.identifier)
    if existing is not None and existing.id != current_user.id:
        raise _ACCOUNT_EXISTS

    current_user.phone = verified.identifier
    current_user.is_phone_verified = True
    db.commit()
    db.refresh(current_user)
    return UserOut.model_validate(current_user)


@router.post("/email/start", response_model=MessageResponse)
def add_email_start(
    payload: AddEmailStartRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
    current_user: User = Depends(get_current_user),
) -> MessageResponse:
    """Symmetric to /auth/phone/start, for verifying/replacing the
    email on the logged-in account — e.g. a customer who signed up
    phone-first, and now wants email notifications/receipts too. The
    OTP row is keyed by the new email itself, same as any other
    identifier."""
    rate_limit_by_ip_and_phone(redis, request, payload.email, "add_email_start")
    existing = _verified_email_owner(db, payload.email)
    if existing is not None and existing.id != current_user.id:
        raise _EMAIL_EXISTS

    code = otp_service.create_and_send_otp(
        db, payload.email, OTPPurpose.ADD_EMAIL, channel="email"
    )
    return _message_with_debug_otp(
        f"Verification code sent. It expires in {settings.otp_expire_minutes} minutes.",
        code,
    )


@router.post("/email/verify-otp", response_model=VerificationTokenResponse)
def add_email_verify_otp(
    payload: EmailOtpVerifyRequest,
    request: Request,
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
    _current_user: User = Depends(get_current_user),
) -> VerificationTokenResponse:
    rate_limit_by_ip_and_phone(redis, request, payload.email, "add_email_verify_otp")
    try:
        _, token = otp_service.verify_otp(
            db, payload.email, OTPPurpose.ADD_EMAIL, payload.otp_code
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    return VerificationTokenResponse(
        verification_token=token,
        expires_in_minutes=settings.verification_token_expire_minutes,
    )


@router.post("/email/complete", response_model=UserOut)
def add_email_complete(
    payload: VerificationTokenOnlyRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> UserOut:
    try:
        verified = otp_service.consume_verification_token(
            db, OTPPurpose.ADD_EMAIL, payload.verification_token
        )
    except OTPError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc

    existing = _verified_email_owner(db, verified.identifier)
    if existing is not None and existing.id != current_user.id:
        raise _EMAIL_EXISTS

    current_user.email = verified.identifier
    current_user.is_email_verified = True
    db.commit()
    db.refresh(current_user)
    return UserOut.model_validate(current_user)


@router.patch("/me/marketing-consent", response_model=UserOut)
def update_marketing_consent(
    payload: MarketingConsentRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> UserOut:
    """A standalone, explicit opt-in step — asked after signup, not
    bundled into it, since it's presented as its own screen (see the
    User model docstring on marketing_emails_opt_in)."""
    current_user.marketing_emails_opt_in = payload.opt_in
    db.commit()
    db.refresh(current_user)
    return UserOut.model_validate(current_user)


@router.patch("/me/pin", response_model=MessageResponse)
def change_pin(
    payload: ChangePinRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> MessageResponse:
    """Distinct from the OTP-gated forgot-pin flow (/auth/forgot-pin/*)
    — this is for a logged-in user who still remembers their current
    PIN and just wants to change it, requiring the current PIN as
    proof, same reasoning as google_connect above."""
    if current_user.pin_hash is None or not security.verify_pin(
        payload.current_pin, current_user.pin_hash
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect PIN."
        )

    current_user.pin_hash = security.hash_pin(payload.new_pin)
    db.commit()
    return MessageResponse(message="PIN changed.")


@router.get("/me", response_model=UserOut)
def read_current_user(current_user: User = Depends(get_current_user)) -> UserOut:
    return UserOut.model_validate(current_user)
