from odoo import http
from odoo.http import request
from odoo.addons.mail.tools.discuss import Store


class TierMailboxController(http.Controller):
    """HTTP controller for tier mailbox message feeds.

    Follows the same pattern as /mail/inbox/messages, /mail/starred/messages.
    """

    @http.route(
        "/mail/tier_mailbox/<int:mailbox_id>/messages",
        methods=["POST"],
        type="jsonrpc",
        auth="user",
        readonly=True,
    )
    def tier_mailbox_messages(self, mailbox_id, fetch_params=None):
        """Return messages assigned to the given tier.mailbox."""
        # Verify the user has access to this mailbox
        mailbox = request.env["tier.mailbox"].browse(mailbox_id)
        if not mailbox.exists():
            return {"messages": [], "data": {}}

        # Check access: user must be in user_ids or user_ids is empty
        uid = request.env.uid
        if mailbox.user_ids and uid not in mailbox.user_ids.ids:
            return {"messages": [], "data": {}}

        # Find messages that have a mailbox tag pointing to this mailbox
        domain = [
            ("mailbox_tag_ids.mailbox_id", "=", mailbox_id),
        ]
        res = request.env["mail.message"]._message_fetch(domain, **(fetch_params or {}))
        messages = res.pop("messages")
        return {
            **res,
            "data": Store().add(messages, add_followers=True).get_result(),
            "messages": messages.ids,
        }
