# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

import logging
from odoo import models, fields, api

_logger = logging.getLogger(__name__)


class AccountMove(models.Model):
    _inherit = 'account.move'

    def _post(self, soft=True):
        posted = super()._post(soft=soft)
        posted._fi_update_product_costs()
        return posted

    def _fi_update_product_costs(self):
        """Update product costs from vendor bill lines when bills are posted."""
        auto_update = self.env['ir.config_parameter'].sudo().get_param(
            'fusion_inventory.auto_update_cost', 'True'
        )
        if auto_update != 'True':
            return

        for move in self.filtered(lambda m: m.move_type == 'in_invoice'):
            for line in move.invoice_line_ids:
                if not line.product_id or line.price_unit <= 0:
                    continue
                variant = line.product_id
                old_cost = variant.standard_price
                if abs(old_cost - line.price_unit) > 0.001:
                    variant.standard_price = line.price_unit
                    _logger.info(
                        'Cost updated for %s: %.2f -> %.2f (from bill %s)',
                        variant.display_name, old_cost, line.price_unit,
                        move.name)


class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'

    x_fi_suggested_price = fields.Float(
        string='Suggested Price',
        compute='_compute_suggested_price',
        help='Selling price based on cost and the product margin percentage')

    @api.depends('price_unit', 'product_id')
    def _compute_suggested_price(self):
        for line in self:
            margin = 0
            if line.product_id and line.product_id.product_tmpl_id:
                margin = line.product_id.product_tmpl_id.x_fi_margin_pct or 0
            if 0 < margin < 100 and line.price_unit > 0:
                line.x_fi_suggested_price = round(
                    line.price_unit / (1 - margin / 100), 2)
            else:
                line.x_fi_suggested_price = line.price_unit
