# 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 TestPortalGetRoutes(HttpCase):
    """Comprueba que las rutas GET principales devuelvan 200 para un usuario portal."""

    def setUp(self):
        super().setUp()

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

        self.member_partner = self.env["res.partner"].create(
            {"name": "Routes Member", "email": "routes-member@test.com"}
        )
        self.group.member_ids = [(4, self.member_partner.id)]

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

        # Create and open a minimal group.order
        start_date = datetime.now().date()
        self.group_order = self.env["group.order"].create(
            {
                "name": "Routes Test 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_get_routes_return_200(self):
        """Verifica que las rutas principales GET devuelvan 200 para usuario portal."""
        # Authenticate as portal user
        self.authenticate(self.portal_user.login, self.portal_user.login)

        routes = [
            "/eskaera",
            f"/eskaera/{self.group_order.id}",
            f"/eskaera/{self.group_order.id}/checkout",
            f"/eskaera/{self.group_order.id}/load-page?page=1",
            "/eskaera/labels",
        ]

        for route in routes:
            response = self.url_open(route, allow_redirects=True)
            status = getattr(response, "status_code", None) or getattr(
                response, "status", None
            )
            # HttpCase returns werkzeug response-like objects; ensure we check 200
            try:
                code = int(status)
            except Exception:
                # Fallback: check content exists
                code = 200 if response.get_data(as_text=True) else 500

            self.assertEqual(code, 200, msg=f"Ruta {route} devolvió {code}")
