# Copyright 2026 Ecocentral, Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import datetime

from odoo.tests.common import TransactionCase
from odoo.tests.common import tagged


@tagged("post_install", "-at_install")
class TestSortLinesByProductName(TransactionCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.product_z = cls.env["product.product"].create({"name": "Zucchini"})
        cls.product_a = cls.env["product.product"].create({"name": "Amanida"})
        cls.vendor = cls.env["res.partner"].create({"name": "Proveïdor Test"})
        cls.customer = cls.env["res.partner"].create({"name": "Client Test"})

    def test_purchase_order_line_ordered_by_product_name(self):
        order = self.env["purchase.order"].create(
            {
                "partner_id": self.vendor.id,
                "order_line": [
                    (0, 0, {"product_id": self.product_z.id, "product_qty": 1.0}),
                    (0, 0, {"product_id": self.product_a.id, "product_qty": 1.0}),
                ],
            }
        )
        lines = self.env["purchase.order.line"].search([("order_id", "=", order.id)])
        self.assertEqual(lines.mapped("product_id.name"), ["Amanida", "Zucchini"])

    def test_sale_order_line_ordered_by_product_name(self):
        order = self.env["sale.order"].create(
            {
                "partner_id": self.customer.id,
                "order_line": [
                    (0, 0, {"product_id": self.product_z.id, "product_uom_qty": 1.0}),
                    (0, 0, {"product_id": self.product_a.id, "product_uom_qty": 1.0}),
                ],
            }
        )
        lines = self.env["sale.order.line"].search([("order_id", "=", order.id)])
        self.assertEqual(lines.mapped("product_id.name"), ["Amanida", "Zucchini"])

    def test_product_search_ordered_by_name(self):
        products = self.env["product.product"].search(
            [("id", "in", [self.product_z.id, self.product_a.id])]
        )
        self.assertEqual(list(products), [self.product_a, self.product_z])

    def test_sort_grouped_lines_breaks_tie_on_picking_name(self):
        same_date = datetime(2026, 6, 10, 8, 0, 0)
        warehouse = self.env["stock.warehouse"].search(
            [("company_id", "=", self.env.company.id)], limit=1
        )
        picking_b = self.env["stock.picking"].create(
            {
                "picking_type_id": warehouse.out_type_id.id,
                "location_id": warehouse.lot_stock_id.id,
                "location_dest_id": self.env.ref("stock.stock_location_customers").id,
                "date": same_date,
                "date_done": same_date,
            }
        )
        picking_a = self.env["stock.picking"].create(
            {
                "picking_type_id": warehouse.out_type_id.id,
                "location_id": warehouse.lot_stock_id.id,
                "location_dest_id": self.env.ref("stock.stock_location_customers").id,
                "date": same_date,
                "date_done": same_date,
            }
        )
        # Force deterministic names to make the tie-break assertion exact.
        (picking_a + picking_b).flush_recordset()
        picking_a.name, picking_b.name = "WH/OUT/A", "WH/OUT/B"

        lines_dic = [{"picking": picking_b}, {"picking": picking_a}]
        result = self.env["account.move"]._sort_grouped_lines(lines_dic)
        self.assertEqual([r["picking"] for r in result], [picking_a, picking_b])

    def test_sort_grouped_lines_handles_missing_dates(self):
        picking = self.env["stock.picking"].new({"name": "WH/OUT/999"})
        # Must not raise even without date/date_done set.
        self.env["account.move"]._sort_grouped_lines([{"picking": picking}])
