from __future__ import annotations

import json
import unittest
from urllib.error import HTTPError

from integrations import (
    IntegrationError,
    WooCommerceConfig,
    WooCommerceIntegration,
    execute_integration_action,
    normalize_iran_phone,
)


class FakeResponse:
    def __init__(self, payload):
        self.raw = json.dumps(payload).encode("utf-8")

    def __enter__(self):
        return self

    def __exit__(self, *_):
        return False

    def read(self, limit=-1):
        return self.raw[:limit]


class WooCommerceIntegrationTests(unittest.TestCase):
    def config(self):
        return WooCommerceConfig(
            base_url="https://arcopet.com",
            consumer_key="ck_read_only",
            consumer_secret="cs_secret",
            timeout=7,
        )

    def test_normalizes_iranian_phone_formats(self):
        self.assertEqual(normalize_iran_phone("+98 912-345-6789"), "09123456789")
        self.assertEqual(normalize_iran_phone("۰۹۱۲۳۴۵۶۷۸۹"), "09123456789")
        self.assertEqual(normalize_iran_phone("9123456789"), "09123456789")

    def test_get_order_returns_only_safe_fields(self):
        seen = {}

        def transport(request, timeout):
            seen["url"] = request.full_url
            seen["authorization"] = request.get_header("Authorization")
            seen["timeout"] = timeout
            return FakeResponse(
                {
                    "id": 1460469,
                    "number": "1460469",
                    "status": "ronadsend",
                    "billing": {"phone": "+989123456789", "first_name": "مشتری"},
                    "shipping": {"address_1": "نباید نمایش داده شود"},
                    "meta_data": [
                        {"key": "_delivery_date", "value": "1405/06/27"},
                        {"key": "_delivery_time", "value": "15–21"},
                        {"key": "post_track_number", "value": "POST-123"},
                    ],
                }
            )

        result = WooCommerceIntegration(self.config(), transport).get_order(
            "۱۴۶۰۴۶۹", "09123456789"
        )
        self.assertEqual(result["number"], "1460469")
        self.assertEqual(result["status_label"], "ارسال‌شده")
        self.assertEqual(result["tracking_number"], "POST-123")
        self.assertNotIn("billing", result)
        self.assertNotIn("shipping", result)
        self.assertEqual(seen["url"], "https://arcopet.com/wp-json/wc/v3/orders/1460469")
        self.assertTrue(seen["authorization"].startswith("Basic "))
        self.assertEqual(seen["timeout"], 7)

    def test_phone_mismatch_uses_generic_not_found_error(self):
        client = WooCommerceIntegration(
            self.config(),
            lambda *_: FakeResponse(
                {"id": 1, "status": "processing", "billing": {"phone": "09120000000"}}
            ),
        )
        with self.assertRaises(IntegrationError) as raised:
            client.get_order("1", "09121111111")
        self.assertEqual(raised.exception.code, "order_not_found")
        self.assertNotIn("0912", raised.exception.public_message)

    def test_http_404_is_safe_not_found(self):
        def transport(request, _):
            raise HTTPError(request.full_url, 404, "Not Found", {}, None)

        with self.assertRaises(IntegrationError) as raised:
            WooCommerceIntegration(self.config(), transport).get_order("99", "09123456789")
        self.assertEqual(raised.exception.code, "order_not_found")

    def test_missing_brand_endpoint_does_not_look_like_order_not_found(self):
        def transport(request, _):
            raise HTTPError(request.full_url, 404, "Not Found", {}, None)

        with self.assertRaises(IntegrationError) as raised:
            WooCommerceIntegration(self.config(), transport)._request("products/brands?per_page=100", with_headers=True)
        self.assertEqual(raised.exception.code, "taxonomy_not_found")

    def test_arbitrary_actions_are_rejected(self):
        result = execute_integration_action("http.request", {"url": "https://example.com"})
        self.assertFalse(result["ok"])
        self.assertEqual(result["error"]["code"], "unsupported_action")


if __name__ == "__main__":
    unittest.main()
