# Copyright 2026 Criptomart
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields
from odoo import models


class StockPicking(models.Model):
    _inherit = "stock.picking"

    batch_consumer_group_id = fields.Many2one(
        comodel_name="res.partner",
        compute="_compute_batch_consumer_group_id",
        readonly=True,
        string="Batch Consumer Group",
    )

    def _compute_batch_consumer_group_id(self):
        for picking in self:
            sale = picking.sale_id if "sale_id" in picking._fields else False
            if sale and "consumer_group_id" in sale._fields:
                picking.batch_consumer_group_id = sale.consumer_group_id
            else:
                picking.batch_consumer_group_id = False

    def _pre_action_done_hook(self):
        """Run collected checks only after Odoo resolves backorders.

        This keeps the product summary checkbox informative during the initial
        batch validation click, but still enforces it once the user confirms the
        actual picking flow that will be processed.
        """

        res = super()._pre_action_done_hook()
        if res is not True:
            return res

        self._check_batch_collected_products()
        return res

    def _check_batch_collected_products(self):
        for batch in self.batch_id:
            batch_pickings = self.filtered(
                lambda picking, batch=batch: picking.batch_id == batch
            )
            processed_move_lines = batch_pickings.move_line_ids.filtered(
                lambda line: (
                    line.move_id.state not in ("cancel", "done")
                    and line.product_id
                    and line.move_id.quantity > 0
                )
            )
            if not processed_move_lines:
                continue
            batch._check_all_products_collected(batch_pickings)
