# Copyright (C) 2020: Criptomart (https://criptomart.net)
# @author Santi Noreña (<santi@criptomart.net>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

# import logging

from odoo import api, fields, models

# _logger = logging.getLogger(__name__)


class ProductPricelist(models.Model):
    _inherit = "product.pricelist"

    price_rounding_step = fields.Float(
        string="Sale Price Rounding Step",
        digits=(12, 2),
        default=0.0,
        help="Round the theoretical sale price (after taxes) to the nearest multiple of this value. "
        "Set to 0.00 to disable rounding (e.g. 0.05 rounds to the nearest 5 cents).",
    )
    price_rounding_method = fields.Selection(
        [
            ("up", "Always up (ceil)"),
            ("down", "Always down (floor)"),
            ("round", "Nearest (round)"),
        ],
        string="Sale Price Rounding Method",
        default="round",
        required=True,
        help="Direction to apply when rounding the theoretical sale price to the configured step.\n"
        "* Always up: rounds to the next multiple (ceil).\n"
        "* Always down: rounds to the previous multiple (floor).\n"
        "* Nearest: rounds to the closest multiple (standard round).",
    )

    def _compute_price_rule(self, products, qty, uom=None, date=False, **kwargs):
        ProductPricelistItem = self.env["product.pricelist.item"]
        ProductProduct = self.env["product.product"]
        res = super()._compute_price_rule(
            products,
            qty=qty,
            uom=uom,
            date=date,
        )
        new_res = res.copy()
        item_id = []
        for product_id, values in res.items():
            if values[1]:
                item_id = values[1]
            if item_id:
                item = ProductPricelistItem.browse(item_id)
                if item.base == "last_purchase_price":
                    price = ProductProduct.browse(
                        product_id
                    ).last_purchase_price_received
                    price = (price - (price * (item.price_discount / 100))) or 0.0
                    new_res[product_id] = (price, item_id)
        return new_res
