import logging
import smtplib
from email.message import EmailMessage
from fastapi import APIRouter, HTTPException, Request, status
from app.config import settings
from app.security.rate_limit import limiter
from app.schemas.api import ContactRequest

router = APIRouter(tags=["contact"])
logger = logging.getLogger(__name__)


@router.post("/contact", status_code=status.HTTP_204_NO_CONTENT)
@limiter.limit("5/minute")
def send_contact(request: Request, body: ContactRequest):
    if body.website:
        # honeypot: los bots suelen rellenar todos los campos, incluido este oculto
        return

    if not settings.SMTP_HOST or not settings.CONTACT_TO_EMAIL:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="El formulario de contacto no está configurado",
        )

    msg = EmailMessage()
    msg["Subject"] = f"MT2MX — solicitud de acceso de {body.name}"
    msg["From"] = settings.SMTP_USER
    msg["To"] = settings.CONTACT_TO_EMAIL
    msg["Reply-To"] = body.email
    msg.set_content(
        f"Nombre: {body.name}\n"
        f"Correo: {body.email}\n"
        f"Empresa: {body.company or '-'}\n\n"
        f"Mensaje:\n{body.message}\n"
    )

    try:
        with smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT) as server:
            server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
            server.send_message(msg)
    except Exception as e:
        logger.error(f"Fallo al enviar correo de contacto: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_502_BAD_GATEWAY,
            detail="No se pudo enviar el mensaje, intenta de nuevo más tarde",
        )
