"""Security helpers for admin authentication."""

import hashlib
import bcrypt
from datetime import datetime, timedelta, timezone
from typing import Optional

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt

from .config import settings
from .database import get_session
from .models.admin_user import AdminUser

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")


def _normalize_password(password: str) -> str:
    """
    Normalize password to handle bcrypt's 72-byte limitation.
    For passwords longer than 72 bytes, use SHA256 hash first.
    """
    password_bytes = password.encode('utf-8')
    if len(password_bytes) > 72:
        # Hash with SHA256 first to reduce length
        return hashlib.sha256(password_bytes).hexdigest()
    return password


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Verify a password against its bcrypt hash."""
    normalized = _normalize_password(plain_password)
    return bcrypt.checkpw(normalized.encode('utf-8'), hashed_password.encode('utf-8'))


def hash_password(password: str) -> str:
    """Hash a password using bcrypt."""
    normalized = _normalize_password(password)
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(normalized.encode('utf-8'), salt).decode('utf-8')


def create_access_token(subject: str, expires_minutes: Optional[int] = None) -> str:
    expire = datetime.now(timezone.utc) + timedelta(minutes=expires_minutes or settings.admin_token_exp_minutes)
    to_encode = {"sub": subject, "exp": expire}
    return jwt.encode(to_encode, settings.admin_jwt_secret, algorithm="HS256")


def decode_token(token: str) -> str:
    try:
        payload = jwt.decode(token, settings.admin_jwt_secret, algorithms=["HS256"])
        return payload.get("sub")
    except JWTError as exc:  # pragma: no cover - FastAPI handles
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token invalide") from exc


async def get_current_admin(token: str = Depends(oauth2_scheme), session=Depends(get_session)) -> AdminUser:
    email = decode_token(token)
    if not email:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token invalide")

    admin = session.query(AdminUser).filter(AdminUser.email == email).first()
    if not admin:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin introuvable")

    if settings.admin_allowed_domains:
        domain = email.split("@")[-1].lower()
        allowed = {item.lower() for item in settings.admin_allowed_domains}
        if domain not in allowed:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Compte non autorisé")
    return admin


def require_roles(*allowed_roles: str):
    async def dependency(admin: AdminUser = Depends(get_current_admin)) -> AdminUser:
        if allowed_roles and admin.role not in allowed_roles:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Accès refusé")
        return admin

    return dependency
