"""Shared password-reset OTP flow for admin and member accounts."""

from __future__ import annotations

from sqlalchemy import func
from sqlalchemy.orm import Session

from app.database import release_db_connection
from app.models import User, UserRole
from app.services.email_otp import create_password_reset_flow, send_password_reset_email


def normalize_email(email: str) -> str:
    return email.strip().lower()


def find_user_by_email(db: Session, email: str, *, role: UserRole | None = None) -> User | None:
    normalized = normalize_email(email)
    q = db.query(User).filter(func.lower(User.email) == normalized)
    if role is not None:
        q = q.filter(User.role == role)
    return q.first()


async def send_password_reset_otp(db: Session, user: User) -> str:
    """Create OTP row and email it. Raises if SMTP delivery fails."""
    otp = create_password_reset_flow(db, user)
    recipient = user.email
    release_db_connection(db)
    sent = await send_password_reset_email(recipient, otp)
    if not sent:
        raise RuntimeError(
            "Could not send password reset email. Check SMTP settings on the server."
        )
    return otp
