#wp_invoices_mail_app/auth.py
from email.message import Message
from typing import Optional, Tuple

from shared.wp_invoices_auth import check_credentials


def get_plain_body(msg: Message) -> str:
    """
    Devuelve el cuerpo en texto plano del mensaje.
    """
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == "text/plain":
                charset = part.get_content_charset() or "utf-8"
                try:
                    return part.get_payload(decode=True).decode(
                        charset, errors="ignore"
                    )
                except Exception:
                    continue
    else:
        charset = msg.get_content_charset() or "utf-8"
        try:
            return msg.get_payload(decode=True).decode(charset, errors="ignore")
        except Exception:
            pass

    return ""


def parse_credentials_from_body(body: str) -> Optional[Tuple[str, str]]:
    """
    Busca líneas del estilo:
      USER: algo
      PASS: algo
    y devuelve (user, pass) si las encuentra.
    """
    user = None
    pwd = None

    for line in body.splitlines():
        line = line.strip()
        if line.lower().startswith("user:"):
            user = line.split(":", 1)[1].strip()
        elif line.lower().startswith("pass:"):
            pwd = line.split(":", 1)[1].strip()

    if user and pwd:
        return user, pwd
    return None


def is_authorized_from_message(msg: Message) -> Tuple[bool, str]:
    """
    Lee el cuerpo del mensaje, extrae USER/PASS y valida contra la lista
    de usuarios permitidos. Devuelve (autorizado, mensaje_log).
    """
    body = get_plain_body(msg)
    creds = parse_credentials_from_body(body)

    if not creds:
        return "NOT_CREDENTIALS", ""

    user, pwd = creds
    if not check_credentials(user, pwd):
        return "INVALID_CREDENTIALS", f"Credenciales inválidas para user={user!r}."

    return "AUTH", f"Autenticado user={user!r}."
