import json
import logging

from odoo import http
from odoo.http import request

_logger = logging.getLogger(__name__)


class MatrixWebhookController(http.Controller):
    """HTTP controller for incoming Matrix push events.

    Matrix homeserver pushes events to this endpoint.
    Incoming message → create mail.message in Odoo with 'matrix' channel tag.
    """

    @http.route(
        '/tier_matrix/webhook',
        type='http',
        auth='public',
        methods=['POST'],
        csrf=False,
    )
    def matrix_webhook(self, **kwargs):
        """Receive a Matrix event and create a mail.message in Odoo."""
        try:
            payload = json.loads(request.httprequest.data or '{}')
        except (ValueError, TypeError):
            _logger.warning('tier_matrix webhook: invalid JSON payload')
            return request.make_response(
                json.dumps({'error': 'invalid JSON'}),
                headers=[('Content-Type', 'application/json')],
                status=400,
            )

        event_type = payload.get('type', '')
        if event_type != 'm.room.message':
            return request.make_response(
                json.dumps({'status': 'ignored'}),
                headers=[('Content-Type', 'application/json')],
            )

        try:
            request.env['tier.channel.matrix.helper'].sudo().channel_receive_message(payload)
        except Exception:
            _logger.exception('tier_matrix webhook: error processing event')
            return request.make_response(
                json.dumps({'error': 'processing error'}),
                headers=[('Content-Type', 'application/json')],
                status=500,
            )

        return request.make_response(
            json.dumps({'status': 'ok'}),
            headers=[('Content-Type', 'application/json')],
        )
