# -*- coding: utf-8 -*-
"""STEP 11 — DocuSeal webhook endpoint.

Thin controller: validates a shared secret, then delegates to the document model's
_process_signature_event handler (which is what the unit tests exercise). This route
is the ONE internet-facing endpoint in an otherwise NetBird-internal stack — keep it
hardened (shared secret here; isolate the DocuSeal host itself at the infra layer).
"""

import logging

from odoo import http
from odoo.http import request

_logger = logging.getLogger(__name__)

PARAM_SECRET = "familylaw.docuseal_webhook_secret"


class FamilyLawDocusealController(http.Controller):

    @http.route("/familylaw/docuseal/webhook", type="json",
                auth="public", csrf=False, methods=["POST"])
    def docuseal_webhook(self, **kwargs):
        # shared-secret check (header or payload). Fail closed if a secret is set.
        secret = request.env["ir.config_parameter"].sudo().get_param(PARAM_SECRET)
        if secret:
            provided = request.httprequest.headers.get("X-Docuseal-Secret")
            if provided != secret:
                _logger.warning("DocuSeal webhook rejected: bad secret.")
                return {"ok": False, "error": "unauthorized"}

        payload = request.get_json_data() if hasattr(request, "get_json_data") else {}
        # DocuSeal payloads vary; accept common shapes.
        data = payload.get("data", payload) or {}
        submission_id = (data.get("submission_id") or data.get("id")
                         or payload.get("submission_id"))
        status = payload.get("event_type") or data.get("status") or payload.get("status")
        # normalise common DocuSeal event names
        if status in ("submission.completed", "form.completed"):
            status = "completed"
        request.env["familylaw.document"].sudo()._process_signature_event(
            submission_id, status)
        return {"ok": True}
