# SPDX-FileCopyrightText: 2025 Max Mehl <https://mehl.mx>
#
# SPDX-License-Identifier: Apache-2.0

"""Messages blueprint for CastMail2List application"""

from flask import Blueprint, flash, render_template, url_for
from flask_babel import _
from flask_login import login_required

from ..models import EmailIn, EmailOut
from ..utils import (
    get_all_incoming_messages,
    get_all_outgoing_messages,
    get_message_id_in_db,
)

messages = Blueprint("messages", __name__, url_prefix="/messages")


@messages.before_request
@login_required
def before_request() -> None:
    """Require login for all routes"""


@messages.route("/")
def index() -> str:
    """Show all normal incoming messages"""
    msgs: list[EmailIn] = get_all_incoming_messages(only="ok")
    return render_template("messages/index.html", messages=msgs)


@messages.route("/bounces")
def bounces() -> str:
    """Show only bounced messages"""
    return render_template(
        "messages/bounces.html", messages=get_all_incoming_messages(only="bounces")
    )


@messages.route("/failures")
def failures() -> str:
    """Show only failure messages (except bounces)"""
    return render_template(
        "messages/failures.html", messages=get_all_incoming_messages(only="failures")
    )


@messages.route("/sent")
def sent() -> str:
    """Show all outgoing messages"""
    return render_template("messages/sent.html", messages=get_all_outgoing_messages())


@messages.route("/<message_id>")
def show(message_id: str) -> str:
    """Show a specific message, without list context"""
    msgs: list[EmailIn | EmailOut] = get_message_id_in_db([message_id])

    if len(msgs) == 1:
        msg = msgs[0]
        msg_type = "out" if isinstance(msg, EmailOut) else "in"
        bounce = getattr(msg, "status", "") == "bounce-msg"
        return render_template(
            "messages/detail.html", message=msg, msg_type=msg_type, bounce=bounce
        )

    if len(msgs) > 1:
        flash(
            _("Multiple messages found with the same Message-ID. Please choose from below."),
            "warning",
        )
        return render_template("messages/detail.html", message=None, multiple_msgs=msgs)

    # Fallback: Message not found
    flash(_("Message not found"), "error")
    return render_template("messages/detail.html", message=None)


@messages.route("<message_id>/<list_id>")
def show_unique(message_id: str, list_id: str) -> str:
    """Show a specific message, with list context"""
    msgs: list[EmailIn | EmailOut] = get_message_id_in_db([message_id])

    msg_unique: EmailIn | EmailOut
    if len(msgs) > 1:
        msg_unique = get_message_id_in_db([message_id], list_id=list_id)[0]
        flash(
            _(
                "Multiple messages found with the same Message-ID. Showing message for the "
                "selected list. See <a href='%(link)s'>here</a> for the other messages.",
                link=url_for("messages.show", message_id=message_id),
            ),
            "message",
        )
    elif len(msgs) == 1:
        msg_unique = msgs[0]
    else:
        # Message not found
        flash(_("Message not found"), "error")
        return render_template("messages/detail.html", message=None)

    msg_type = "out" if isinstance(msg_unique, EmailOut) else "in"
    bounce = getattr(msg_unique, "status", "") == "bounce-msg"
    return render_template(
        "messages/detail.html", message=msg_unique, msg_type=msg_type, bounce=bounce
    )
