# 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 TestPortalAccess(HttpCase):
    """Verifica que un usuario portal pueda acceder a la página de un pedido (eskaera)."""

    def setUp(self):
        super().setUp()
        # Create a consumer group and a member partner
        self.group = self.env["res.partner"].create(
            {
                "name": "Portal Test Group",
                "is_company": True,
                "email": "portal-group@test.com",
            }
        )

        self.member_partner = self.env["res.partner"].create(
            {
                "name": "Portal Member",
                "email": "portal-member@test.com",
            }
        )

        # Add member to the group
        self.group.member_ids = [(4, self.member_partner.id)]

        # Create a portal user (password = login for HttpCase.authenticate convenience)
        login = "portal.user@test.com"
        self.portal_user = self.env["res.users"].create(
            {
                "name": "Portal User",
                "login": login,
                "password": login,
                "partner_id": self.member_partner.id,
                # Add portal group
                "groups_id": [(4, self.env.ref("base.group_portal").id)],
            }
        )

        # Create and open a group.order belonging to the same company
        start_date = datetime.now().date()
        self.group_order = self.env["group.order"].create(
            {
                "name": "Portal Access 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",
            }
        )
        self.group_order.action_open()

    def test_portal_user_can_view_eskaera_page(self):
        """El endpoint /eskaera/<id> debe ser accesible por un usuario portal que pertenezca a la compañía."""
        # Authenticate as portal user
        self.authenticate(self.portal_user.login, self.portal_user.login)

        # Request the eskaera page
        response = self.url_open(
            f"/eskaera/{self.group_order.id}", allow_redirects=True
        )

        # Should return 200 OK and not redirect to login
        self.assertEqual(response.status_code, 200)
        # Simple sanity: page should contain the group order name
        content = (
            response.get_data(as_text=True)
            if hasattr(response, "get_data")
            else getattr(response, "text", "")
        )
        self.assertIn(self.group_order.name, content)
