"""Paymob payment order tracking.

We keep an auditable trail of every checkout we initiate with Paymob so we
can (a) show users the status of their payments, (b) reconcile against the
Paymob dashboard, and (c) prove/dispute webhook events with the signed
HMAC we stored.

Lifecycle:

* ``draft``      — row created but no Paymob API call made yet
* ``initiated``  — authentication + order registration succeeded, we have a
                   ``payment_key`` we can redirect the user to
* ``paid``       — the ``TRANSACTION`` webhook fired with ``success=true``
                   and a verified HMAC
* ``failed``     — webhook fired with ``success=false``
* ``cancelled``  — user abandoned / timed out (set manually or by cron)
"""

from odoo import fields, models


class EncoachPaymobOrder(models.Model):
    _name = "encoach.paymob.order"
    _description = "Paymob payment order"
    _order = "create_date desc"
    _rec_name = "reference"

    reference = fields.Char(
        required=True, index=True,
        help="Our merchant order reference; included in the Paymob request.",
    )
    user_id = fields.Many2one(
        "res.users", required=True, ondelete="restrict", index=True,
    )
    partner_id = fields.Many2one("res.partner", ondelete="set null")

    # Commerce fields
    amount_cents = fields.Integer(
        required=True,
        help="Amount in smallest currency unit (piastres for EGP).",
    )
    currency = fields.Char(required=True, default="EGP")
    description = fields.Char()
    product_ref = fields.Char(
        help="Free-text link back to the thing being bought "
        "(e.g. 'subscription:pro-monthly').",
    )

    # Paymob identifiers
    paymob_order_id = fields.Char(index=True)
    payment_key = fields.Text()
    payment_key_expires_at = fields.Datetime()
    integration_id = fields.Char(
        help="Which Paymob integration was used (card / wallet / kiosk...)",
    )

    # State
    state = fields.Selection(
        [
            ("draft", "Draft"),
            ("initiated", "Initiated"),
            ("paid", "Paid"),
            ("failed", "Failed"),
            ("cancelled", "Cancelled"),
        ],
        default="draft", required=True, index=True,
    )
    last_event_at = fields.Datetime()
    last_event_payload = fields.Text(
        help="JSON of the latest webhook payload we received for this order.",
    )
    last_event_hmac = fields.Char(
        help="HMAC we verified against the payload; stored for audit.",
    )

    def mark_paid(self, payload, hmac):
        self.ensure_one()
        self.write({
            "state": "paid",
            "last_event_at": fields.Datetime.now(),
            "last_event_payload": payload,
            "last_event_hmac": hmac,
        })

    def mark_failed(self, payload, hmac):
        self.ensure_one()
        self.write({
            "state": "failed",
            "last_event_at": fields.Datetime.now(),
            "last_event_payload": payload,
            "last_event_hmac": hmac,
        })
