from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import float_round


class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    product_uom_ordered_qty = fields.Float(
        string="Ordered Qty", digits="Product Unit of Measure", default=0.0
    )
    product_uom_max_qty = fields.Float(
        string="Max Qty", digits="Product Unit of Measure"
    )
    batch_uom_qty = fields.Float(
        related="batch_product_id.product_uom_qty", string="Batch UOM Qty"
    )
    batch_uom_max_qty = fields.Float(
        related="batch_product_id.product_uom_max_qty", string="Batch UOM Max Qty"
    )

    @api.constrains("product_uom_qty", "product_uom_max_qty")
    def _check_product_uom_qty(self):
        for order_line in self:
            if (
                float_round(
                    order_line.product_uom_max_qty - order_line.product_uom_qty,
                    precision_rounding=order_line.product_uom.rounding,
                )
                < 0
            ):
                raise UserError(
                    _(
                        f"{order_line.order_id.name}, {order_line.product_id.name}: "
                        "The quantity must be less than or equal to the maximum quantity."
                    )
                )

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            product_qty = vals.get("product_uom_qty", 0.0)
            if (
                not vals.get("product_uom_max_qty")
                or vals.get("product_uom_max_qty") == 0
            ):
                vals["product_uom_max_qty"] = product_qty
            if not vals.get("product_uom_ordered_qty"):
                vals["product_uom_ordered_qty"] = product_qty
            if vals.get("product_id") and not vals.get("product_packaging_id"):
                product_id = vals.get("product_id")
                # Make sure we're not sudo
                # e.x. when coming from webshop
                packaging = self.env["product.packaging"].search(
                    [
                        ("product_id", "=", product_id),
                        ("company_id", "in", [False, self.env.company.id]),
                    ],
                    limit=1,
                )
                vals["product_packaging_id"] = packaging.id
        return super().create(vals_list)

    def write(self, vals):
        product_qty = vals.get("product_uom_qty")
        product_max_qty = vals.get("product_uom_max_qty")
        if product_qty and product_max_qty and product_qty > product_max_qty:
            vals["product_uom_max_qty"] = product_qty
        elif product_qty:
            for line in self:
                if product_qty > line.product_uom_max_qty:
                    line["product_uom_max_qty"] = product_qty
        return super().write(vals)
