"""Rotas Email Relay VM122 — configuração visível no portal Infra."""

from __future__ import annotations

from pydantic import BaseModel, Field

from fastapi import APIRouter, Depends, HTTPException

from app import auth, email_relay

router = APIRouter(prefix="/api/v1/infra/email-relay", tags=["infra-email-relay"])


def _can_manage(user: auth.DeskUser) -> bool:
    return user.role in ("super_admin", "devops")


def _can_view(user: auth.DeskUser) -> bool:
    return user.role in ("super_admin", "devops", "developer")


class EmailRelayTestBody(BaseModel):
    to: str = Field(min_length=3, max_length=254)
    subject: str | None = Field(default=None, max_length=200)


@router.get("/status")
def email_relay_status(user: auth.DeskUser = Depends(auth.get_current_user)):
    if not _can_view(user):
        raise HTTPException(403, "permissão insuficiente")
    return email_relay.build_status()


@router.get("/config")
def email_relay_config(user: auth.DeskUser = Depends(auth.get_current_user)):
    if not _can_view(user):
        raise HTTPException(403, "permissão insuficiente")
    return email_relay.load_config()


@router.post("/test")
def email_relay_test(body: EmailRelayTestBody, user: auth.DeskUser = Depends(auth.get_current_user)):
    if not _can_manage(user):
        raise HTTPException(403, "permissão insuficiente")
    return email_relay.send_test_email(body.to, body.subject)
