from odoo import _, models, fields
from odoo.exceptions import ValidationError


class StockQuant(models.Model):
    _inherit = "stock.quant"

    product_categ_id = fields.Many2one(
        related="product_tmpl_id.categ_id",
        store=True,
        index=True,
        string="Product Category",
    )


class InventoryAdjustmentsGroup(models.Model):
    _inherit = "stock.inventory"

    def action_state_to_in_progress(self):
        self.ensure_one()
        search_filter = [
            (
                "location_id",
                "child_of" if not self.exclude_sublocation else "in",
                self.location_ids.ids,
            ),
            ("to_do", "=", True),
        ]

        error_field = "location_id"
        error_message = _(
            "There's already an Adjustment in Process "
            "using one requested Location: %(names)s. "
            "Blocking adjustments: %(blocking_names)s"
        )

        if self.product_ids:
            search_filter.append(("product_id", "in", self.product_ids.ids))
            error_field = "product_id"
            error_message = _(
                "There are active adjustments for the requested products: %(names)s. "
                "Blocking adjustments: %(blocking_names)s"
            )
        elif self.category_id:
            # Solo misma categoría exacta, sin OR hijos
            search_filter.append(("product_id.categ_id", "=", self.category_id.id))
            error_field = "category_id"
            error_message = _(
                "There are active adjustments for the requested category: %(names)s. "
                "Blocking adjustments: %(blocking_names)s"
            )

        quants = self.env["stock.quant"].search(search_filter)
        if quants:
            inventory_ids = self.env["stock.inventory"].search(
                [("stock_quant_ids", "in", quants.ids), ("state", "=", "in_progress")]
            )
            if inventory_ids:
                blocking_names = ", ".join(inventory_ids.mapped("name"))
                names = self._get_quant_joined_names(quants, error_field)
                raise ValidationError(
                    error_message % {"names": names, "blocking_names": blocking_names}
                )

        quants = self._get_quants(self.location_ids)
        self.write({"state": "in_progress", "stock_quant_ids": [(6, 0, quants.ids)]})
        quants.write(
            {
                "to_do": True,
                "user_id": self.responsible_id,
                "inventory_date": self.date,
                "current_inventory_id": self.id,
            }
        )
        return
