# Part of Odoo. See LICENSE file for full copyright and licensing details.

import logging

from odoo import _, fields, models
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)


class PaymentToken(models.Model):
    _inherit = 'payment.token'

    poynt_card_id = fields.Char(
        string="Poynt Card ID",
        help="The unique card identifier stored on the Poynt platform.",
        readonly=True,
    )
    poynt_payment_token = fields.Char(
        string="Poynt Payment Token (JWT)",
        help="Long-lived JWT issued by Poynt /cards/tokenize, used for "
             "recurring charges via /cards/tokenize/charge.",
        readonly=True,
        groups='base.group_system',
    )

    def _poynt_validate_stored_card(self):
        """Validate that the stored card is still usable on Poynt.

        Fetches the card details from Poynt to confirm the card ID is valid
        and the card is still active.

        :return: True if the card is valid.
        :rtype: bool
        :raises ValidationError: If the card cannot be validated.
        """
        self.ensure_one()

        if not self.poynt_card_id:
            raise ValidationError(
                _("No Poynt card ID found on this payment token.")
            )

        try:
            result = self.provider_id.sudo()._poynt_make_request(
                'GET',
                f'cards/{self.poynt_card_id}',
            )
            status = result.get('status', '')
            if status != 'ACTIVE':
                raise ValidationError(
                    _("The stored card is no longer active on Poynt (status: %(status)s).",
                      status=status)
                )
            return True
        except ValidationError:
            raise
        except Exception as e:
            _logger.warning("Failed to validate Poynt card %s: %s", self.poynt_card_id, e)
            raise ValidationError(
                _("Unable to validate the stored card with Poynt.")
            )
