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

"""Test portal users can create sale orders with proper permissions."""

import logging
from datetime import datetime
from datetime import timedelta

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

_logger = logging.getLogger(__name__)


@tagged("post_install", "-at_install")
class TestPortalSaleOrderCreation(TransactionCase):
    """Test that portal users can create sale orders through the controller."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        # Create a portal user
        cls.portal_user = cls.env["res.users"].create(
            {
                "name": "Portal Test User",
                "login": "portal_test_user",
                "email": "portal@test.com",
                "groups_id": [(6, 0, [cls.env.ref("base.group_portal").id])],
            }
        )

        # Create a salesperson
        cls.salesperson = cls.env["res.users"].create(
            {
                "name": "Salesperson Test",
                "login": "salesperson_test",
                "email": "sales@test.com",
                "groups_id": [
                    (6, 0, [cls.env.ref("sales_team.group_sale_salesman").id])
                ],
            }
        )

        # Assign salesperson to portal user's partner
        cls.portal_user.partner_id.user_id = cls.salesperson

        # Create a group order for testing
        cls.group_order = cls.env["group.order"].create(
            {
                "name": "Test Group Order",
                "state": "confirmed",
                "pickup_day": "0",  # Monday
                "pickup_date": datetime.now().date() + timedelta(days=7),
                "cutoff_date": datetime.now().date() + timedelta(days=3),
            }
        )

        # Create a test product
        cls.product = cls.env["product.product"].create(
            {
                "name": "Test Product",
                "list_price": 100.0,
                "type": "consu",
            }
        )

    def test_portal_user_can_create_sale_order(self):
        """Test that portal users can create sale orders with sudo()."""
        # Create sale order as portal user
        order_vals = {
            "partner_id": self.portal_user.partner_id.id,
            "order_line": [
                (
                    0,
                    0,
                    {
                        "product_id": self.product.id,
                        "product_uom_qty": 2,
                        "price_unit": 100.0,
                        "name": self.product.name,
                    },
                )
            ],
            "state": "draft",
            "group_order_id": self.group_order.id,
            "user_id": self.salesperson.id,  # Assign salesperson
        }

        # This should work with sudo()
        sale_order = self.env["sale.order"].sudo().create(order_vals)

        self.assertTrue(sale_order.exists())
        self.assertEqual(sale_order.partner_id, self.portal_user.partner_id)
        self.assertEqual(sale_order.user_id, self.salesperson)
        self.assertEqual(len(sale_order.order_line), 1)
        self.assertEqual(sale_order.group_order_id, self.group_order)

    def test_get_salesperson_fallback(self):
        """Test salesperson fallback to commercial partner."""
        # Create commercial partner with salesperson
        commercial_partner = self.env["res.partner"].create(
            {
                "name": "Commercial Partner",
                "is_company": True,
                "user_id": self.salesperson.id,
            }
        )

        # Create child contact without salesperson
        child_partner = self.env["res.partner"].create(
            {
                "name": "Child Contact",
                "parent_id": commercial_partner.id,
            }
        )

        # Child should fallback to commercial partner's salesperson
        self.assertEqual(child_partner.commercial_partner_id.user_id, self.salesperson)

    def test_portal_user_can_update_order_lines(self):
        """Test that portal users can update existing order lines with sudo()."""
        # Create initial order
        sale_order = (
            self.env["sale.order"]
            .sudo()
            .create(
                {
                    "partner_id": self.portal_user.partner_id.id,
                    "state": "draft",
                    "group_order_id": self.group_order.id,
                    "user_id": self.salesperson.id,
                    "order_line": [
                        (
                            0,
                            0,
                            {
                                "product_id": self.product.id,
                                "product_uom_qty": 1,
                                "price_unit": 100.0,
                                "name": self.product.name,
                            },
                        )
                    ],
                }
            )
        )

        # Update order line as portal user (with sudo)
        existing_line = sale_order.order_line[0]
        existing_line.sudo().write({"product_uom_qty": 5})

        self.assertEqual(existing_line.product_uom_qty, 5)
