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

import logging
from odoo import models

_logger = logging.getLogger(__name__)


class StockMove(models.Model):
    _inherit = 'stock.move'

    def _action_done(self, cancel_backorder=False):
        res = super()._action_done(cancel_backorder=cancel_backorder)
        try:
            self._trigger_remote_stock_refresh()
        except Exception as e:
            _logger.warning('Remote stock refresh failed (non-blocking): %s', e)
        return res

    def _trigger_remote_stock_refresh(self):
        """After a stock move completes, pull fresh stock data from all
        connected remote instances for the affected products."""
        if not self:
            return

        product_tmpls = self.mapped('product_id.product_tmpl_id')
        if not product_tmpls:
            return

        configs = self.env['fusion.sync.config'].search([
            ('active', '=', True),
            ('state', '=', 'connected'),
            ('sync_stock', '=', True),
        ])

        for config in configs:
            try:
                config._sync_stock_for_products(product_tmpls.ids)
            except Exception as e:
                _logger.warning(
                    'Targeted stock refresh from %s failed: %s',
                    config.name, e)
