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

import json
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import patch

from odoo import fields
from odoo.tests.common import TransactionCase

from ..controllers.website_sale import AplicoopWebsiteSale


class TestGroupOrderStatusEndpoint(TransactionCase):
    """Tests for status endpoint and closed-order safeguards in cart endpoints."""

    def setUp(self):
        super().setUp()
        self.controller = AplicoopWebsiteSale()

        self.group = self.env["res.partner"].create(
            {
                "name": "Status Group",
                "is_company": True,
                "is_group": True,
                "email": "status-group@test.com",
            }
        )

        self.group_order = self.env["group.order"].create(
            {
                "name": "Status Test Order",
                "group_ids": [(6, 0, [self.group.id])],
                "type": "regular",
                "period": "weekly",
                "pickup_day": "3",
                "cutoff_day": "1",
                "start_date": fields.Date.today(),
                "end_date": fields.Date.today() + timedelta(days=7),
            }
        )
        self.group_order.action_open()

        self.product = self.env["product.product"].create(
            {
                "name": "Status Endpoint Product",
                "type": "consu",
                "list_price": 12.0,
            }
        )

    def _build_request_mock(self, payload):
        """Build a request mock with JSON payload and make_response support."""

        def _make_response(data, headers=None, status=200):
            raw = data.encode("utf-8") if isinstance(data, str) else data
            return SimpleNamespace(data=raw, status=status, headers=headers or [])

        return SimpleNamespace(
            env=self.env,
            httprequest=SimpleNamespace(
                data=json.dumps(payload).encode("utf-8"),
            ),
            make_response=_make_response,
        )

    def test_check_group_order_status_open(self):
        """Endpoint returns is_open=True for open group order."""
        request_mock = self._build_request_mock({"order_id": self.group_order.id})

        with patch(
            "odoo.addons.website_sale_aplicoop.controllers.website_sale.request",
            request_mock,
        ):
            response = self.controller.check_group_order_status.__wrapped__(
                self.controller
            )

        data = json.loads(response.data.decode("utf-8"))
        self.assertTrue(data["success"])
        self.assertTrue(data["is_open"])
        self.assertEqual(data["state"], "open")
        self.assertEqual(data["action"], "none")

    def test_check_group_order_status_closed(self):
        """Endpoint returns clear_cart action for non-open group order."""
        self.group_order.action_close()
        request_mock = self._build_request_mock({"order_id": self.group_order.id})

        with patch(
            "odoo.addons.website_sale_aplicoop.controllers.website_sale.request",
            request_mock,
        ):
            response = self.controller.check_group_order_status.__wrapped__(
                self.controller
            )

        data = json.loads(response.data.decode("utf-8"))
        self.assertTrue(data["success"])
        self.assertFalse(data["is_open"])
        self.assertEqual(data["state"], "closed")
        self.assertEqual(data["action"], "clear_cart")

    def test_save_order_endpoint_rejects_closed_group_order(self):
        """/eskaera/save-order must reject closed group order with clear_cart action."""
        self.group_order.action_close()

        payload = {
            "order_id": self.group_order.id,
            "items": [
                {
                    "product_id": self.product.id,
                    "quantity": 1,
                    "product_price": 12.0,
                }
            ],
        }
        request_mock = self._build_request_mock(payload)

        with patch(
            "odoo.addons.website_sale_aplicoop.controllers.website_sale.request",
            request_mock,
        ):
            response = self.controller.save_eskaera_draft.__wrapped__(self.controller)

        data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(response.status, 403)
        self.assertEqual(data.get("code"), "group_order_not_open")
        self.assertEqual(data.get("order_state"), "closed")
        self.assertEqual(data.get("action"), "clear_cart")
