# Copyright 2025 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from odoo import api, fields, models
from odoo.exceptions import AccessError


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

    product_supplier_name = fields.Char(
        string="Supplier Product Name",
        compute="_compute_product_supplier_name",
        store=True,
        help="Product name as defined by the supplier in the product supplier info.",
    )

    @api.depends("partner_id", "product_id")
    def _compute_product_supplier_name(self):
        for line in self:
            name = ""
            if line.product_id and line.partner_id:
                # First try to find exact product match
                supplier_info = line.product_id.seller_ids.filtered(
                    lambda s: (
                        s.product_id == line.product_id
                        and s.partner_id == line.partner_id
                    )
                )
                if supplier_info:
                    name = supplier_info[0].product_name or ""
                else:
                    # If no exact match, try product template
                    supplier_info = line.product_id.seller_ids.filtered(
                        lambda s: (
                            s.product_tmpl_id == line.product_id.product_tmpl_id
                            and s.partner_id == line.partner_id
                        )
                    )
                    if supplier_info:
                        name = supplier_info[0].product_name or ""
            line.product_supplier_name = name


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

    def _add_supplier_to_product(self):
        """Override to also update supplier product name when adding supplier."""
        res = super()._add_supplier_to_product()
        for line in self.order_line:
            partner = (
                self.partner_id
                if not self.partner_id.parent_id
                else self.partner_id.parent_id
            )
            if partner in line.product_id.seller_ids.mapped("partner_id"):
                seller = line.product_id._select_seller(
                    partner_id=line.partner_id,
                    quantity=line.product_qty,
                    date=line.order_id.date_order and line.order_id.date_order.date(),
                    uom_id=line.product_uom,
                )
                if seller and hasattr(line, "product_supplier_name"):
                    try:
                        # Update supplier info with the current product name
                        if line.product_supplier_name:
                            seller.write({"product_name": line.product_supplier_name})
                    except AccessError:
                        break
        return res
