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

from datetime import datetime
from datetime import timedelta

from odoo.tests import tagged
from odoo.tests.common import HttpCase


@tagged("post_install", "-at_install")
class TestPortalProductUoMAccess(HttpCase):
    """Verifica que un usuario portal pueda acceder a la página de tienda (eskaera)
    y que la lectura de UoM para display no provoque AccessError.
    """

    def setUp(self):
        super().setUp()
        # Grupo / partner / usuario portal (reusa patrón del otro test)
        self.group = self.env["res.partner"].create(
            {"name": "Portal UoM Group", "is_company": True}
        )

        self.member_partner = self.env["res.partner"].create(
            {"name": "Portal UoM Member"}
        )
        self.group.member_ids = [(4, self.member_partner.id)]

        login = "portal.uom@test.com"
        self.portal_user = self.env["res.users"].create(
            {
                "name": "Portal UoM User",
                "login": login,
                "password": login,
                "partner_id": self.member_partner.id,
                "groups_id": [(4, self.env.ref("base.group_portal").id)],
            }
        )

        # Crear una categoría de UoM y una UoM personalizada (posible restringida)
        uom_cat = self.env["uom.uom.categ"].create({"name": "Test UoM Cat"})
        self.uom = self.env["uom.uom"].create(
            {
                "name": "Test UoM",
                "uom_type": "reference",
                "factor_inv": 1.0,
                "category_id": uom_cat.id,
            }
        )

        # Crear producto y asignar la UoM creada
        self.product = self.env["product.product"].create(
            {
                "name": "Producto UoM Test",
                "type": "consu",
                "list_price": 12.5,
                "uom_id": self.uom.id,
                "active": True,
            }
        )
        # Publicar el template para que aparezca en la tienda
        self.product.product_tmpl_id.write({"is_published": True, "sale_ok": True})

        # Crear order y añadir producto
        start_date = datetime.now().date()
        self.group_order = self.env["group.order"].create(
            {
                "name": "Portal UoM Order",
                "group_ids": [(6, 0, [self.group.id])],
                "type": "regular",
                "start_date": start_date,
                "end_date": start_date + timedelta(days=7),
                "period": "weekly",
                "pickup_day": "3",
                "cutoff_day": "0",
                "product_ids": [(6, 0, [self.product.id])],
            }
        )
        self.group_order.action_open()

    def test_portal_user_can_view_shop_with_uom(self):
        # Authenticate as portal user
        self.authenticate(self.portal_user.login, self.portal_user.login)

        # Request the eskaera page which renders product cards (and reads uom)
        response = self.url_open(
            f"/eskaera/{self.group_order.id}", allow_redirects=True
        )

        # Debe retornar 200 OK
        self.assertEqual(response.status_code, 200)

        content = (
            response.get_data(as_text=True)
            if hasattr(response, "get_data")
            else getattr(response, "text", "")
        )

        # Página debe contener el nombre del producto y la categoría UoM (display-safe)
        self.assertIn(self.product.name, content)
        self.assertIn("Test UoM Cat", content)
