from odoo import models
from odoo.tools.misc import str2bool


class PurchaseOrderLine(models.Model):
    _inherit = "purchase.order.line"

    _SUPPLIERINFO_DISCOUNT_CONFIG = {
        "discount1": (
            "purchase_order_supplierinfo_update_triple_discount"
            ".update_supplierinfo_discount1"
        ),
        "discount2": (
            "purchase_order_supplierinfo_update_triple_discount"
            ".update_supplierinfo_discount2"
        ),
        "discount3": (
            "purchase_order_supplierinfo_update_triple_discount"
            ".update_supplierinfo_discount3"
        ),
    }

    def write(self, vals):
        res = super().write(vals)
        if any(field in vals for field in self._SUPPLIERINFO_DISCOUNT_CONFIG):
            self.update_supplierinfo_price()
        return res

    def _update_supplierinfo(self, seller):
        """Extend supplierinfo update to optionally sync each discount field."""
        self.ensure_one()
        super()._update_supplierinfo(seller)
        if not seller:
            return

        config = self.env["ir.config_parameter"].sudo()
        values = {}
        for field_name, parameter_name in self._SUPPLIERINFO_DISCOUNT_CONFIG.items():
            if field_name not in self._fields or field_name not in seller._fields:
                continue
            should_update = str2bool(
                config.get_param(parameter_name, default=False),
                default=False,
            )
            if should_update:
                values[field_name] = self[field_name]

        if values:
            seller.sudo().write(values)
