from odoo import models, fields, api, _
import logging

_logger = logging.getLogger(__name__)

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    def action_confirm(self):
        """
        Deduct ingredients when a Website Sale Order is confirmed.
        """
        res = super(SaleOrder, self).action_confirm()
        for order in self:
            # We only deduct for website orders here, as POS orders are handled by action_pos_order_paid
            if order.website_id:
                order._deduct_recipe_ingredients_sale()
        return res

    def _deduct_recipe_ingredients_sale(self):
        self.ensure_one()
        
        # Deduct from Stock to Customers
        location_src_id = self.warehouse_id.lot_stock_id.id
        location_dest_id = self.env.ref('stock.stock_location_customers').id

        moves = []
        for line in self.order_line:
            if not line.product_id:
                continue
                
            recipe = self.env['dine360.recipe'].search([('product_tmpl_id', '=', line.product_id.product_tmpl_id.id)], limit=1)
            
            if recipe:
                for ingredient in recipe.ingredient_ids:
                    total_qty = line.product_uom_qty * ingredient.quantity
                    
                    moves.append({
                        'name': f"Website Recipe Deduction: {line.product_id.name} ({self.name})",
                        'product_id': ingredient.product_id.id,
                        'product_uom': ingredient.uom_id.id,
                        'product_uom_qty': total_qty,
                        'location_id': location_src_id,
                        'location_dest_id': location_dest_id,
                        'origin': self.name,
                        'state': 'draft',
                    })

        if moves:
            _logger.info(f"Dine360 Recipe (Sale): Creating {len(moves)} stock moves for order {self.name}")
            stock_moves = self.env['stock.move'].create(moves)
            stock_moves._action_confirm()
            stock_moves._action_assign()
            for move in stock_moves:
                move.quantity = move.product_uom_qty
            stock_moves._action_done()
