from odoo import _, api, fields, models
from odoo.addons.mail.tools.discuss import Store


class MailMessage(models.Model):
    _inherit = 'mail.message'

    channel_tag_ids = fields.Many2many(
        'tier.channel.tag',
        string='Delivery Channels',
    )
    mailbox_tag_ids = fields.One2many(
        'tier.mailbox.tag',
        'message_id',
        string='Mailbox Tags',
    )

    def _to_store_defaults(self, target):
        """Include channel_tag_ids as plain list of dicts for the frontend."""
        defaults = super()._to_store_defaults(target)
        defaults.append(
            Store.Attr(
                'channel_tag_ids',
                value=lambda m: [
                    {'id': tag.id, 'name': tag.name, 'code': tag.code}
                    for tag in m.channel_tag_ids
                ]
            )
        )
        return defaults

    @api.model
    def get_last_channel_code(self, thread_model, thread_id):
        """Return the channel code of the last message in the thread.

        Used by the composer to auto-select the channel based on the last
        incoming message. Returns None if no channel tag found.
        """
        last_msg = self.search([
            ('model', '=', thread_model),
            ('res_id', '=', thread_id),
            ('channel_tag_ids', '!=', False),
        ], order='id desc', limit=1)
        if last_msg and last_msg.channel_tag_ids:
            return last_msg.channel_tag_ids[0].code
        return None

    def action_move_to_mailbox(self):
        """Open wizard to manually move this message to a mailbox."""
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': _('Переместить в ящик'),
            'res_model': 'tier.move.to.mailbox.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_message_id': self.id,
                'default_current_mailbox_ids': self.mailbox_tag_ids.mapped('mailbox_id').ids,
            },
        }
