from odoo import models


class TierChannelEmail(models.Model):
    """Concrete Email channel implementation.

    Thin wrapper around Odoo's standard mail.mail mechanism.
    Requirements: 3.1, 3.2
    """
    _name = 'tier.channel.email'
    _inherit = ['tier.channel.mixin']
    _description = 'Email Channel'

    def channel_authenticate(self):
        """Email requires no external authentication — always returns True."""
        return True

    def channel_send_message(self, message):
        """Send a mail.message via Odoo's standard mail.mail mechanism."""
        email_to = message.email_from
        if not email_to and message.author_id:
            email_to = message.author_id.email

        mail_mail = self.env['mail.mail'].create({
            'subject': message.subject or '(no subject)',
            'body_html': message.body,
            'email_to': email_to,
            'email_from': self.env.company.email,
        })
        mail_mail.send()

    def channel_receive_message(self, payload):
        """Create a mail.message from an incoming payload dict.

        Expected payload keys:
            body (str): message body HTML
            subject (str, optional): message subject
            email_from (str, optional): sender email address
            author_id (int, optional): res.partner id of the author
        """
        vals = {
            'body': payload.get('body', ''),
            'subject': payload.get('subject', False),
            'email_from': payload.get('email_from', False),
            'message_type': 'email',
        }
        author_id = payload.get('author_id')
        if author_id:
            vals['author_id'] = author_id

        return self.env['mail.message'].create(vals)
