"""Runs the SDK against sdks/testing/mock_server.py:  python -m unittest discover -s tests  (from sdks/python)."""

import importlib.util
import json
import pathlib
import sys
import threading
import unittest
import urllib.request
from datetime import timezone
from decimal import Decimal
from http.server import ThreadingHTTPServer

ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

import hbank  # noqa: E402
from hbank.models import _time  # noqa: E402

spec = importlib.util.spec_from_file_location("mock_server", ROOT.parent / "testing" / "mock_server.py")
mock = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mock)


class ClientTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = ThreadingHTTPServer(("127.0.0.1", 0), mock.Handler)
        cls.base = f"http://127.0.0.1:{cls.server.server_port}"
        mock.BASE = cls.base
        threading.Thread(target=cls.server.serve_forever, daemon=True).start()
        cls.bank = hbank.HBank("test_key", base_url=cls.base)

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()

    def pay(self, tid):
        urllib.request.urlopen(urllib.request.Request(f"{self.base}/_mock/pay/{tid}", method="POST")).read()

    def test_payment_flow(self):
        tid = self.bank.create_payment(Decimal("24.90"), "EUR", description="Order 1042",
                                       callback_url="https://shop.example/cb")
        self.assertEqual(self.bank.checkout_url(tid), f"{self.base}/api/payment?tid={tid}")
        code = self.bank.create_payment_code(tid)
        self.assertTrue(code.qr_svg.endswith("/qr.svg"))
        self.assertEqual(self.bank.create_payment_code(tid).code, code.code)

        p = self.bank.get_payment(tid)
        self.assertEqual((p.status, p.amount, p.description, p.completed), ("pending", Decimal("24.90"), "Order 1042", False))
        self.pay(tid)
        p = self.bank.get_payment(tid)
        self.assertTrue(p.completed)
        self.assertEqual(p.refundable, Decimal("24.90"))

        r = self.bank.refund(tid, "10", reason="Returned one item")
        self.assertEqual((r.refund.amount, r.refund.reason), (Decimal("10"), "Returned one item"))
        self.assertEqual((r.payment.refunded, r.payment.refundable), (Decimal("10"), Decimal("14.90")))
        rest = self.bank.refund(tid)
        self.assertEqual(rest.refund.amount, Decimal("14.90"))
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.refund(tid)
        self.assertEqual((e.exception.code, e.exception.status), ("not_refundable", 409))
        self.assertTrue(e.exception.message)

    def test_amounts_keep_their_digits(self):
        for amount in (24.9, "24.90", 24, Decimal("0.1")):
            tid = self.bank.create_payment(amount, "EUR")
            self.assertEqual(self.bank.get_payment(tid).amount, Decimal(str(amount)).quantize(Decimal("0.01")))

    def test_errors(self):
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.create_payment(0, "EUR")
        self.assertEqual((e.exception.code, e.exception.status), ("invalid_amount", 400))
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.create_payment(1, "XXX")
        self.assertEqual(e.exception.code, "unknown_currency")
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.get_payment(999999)
        self.assertEqual((e.exception.code, e.exception.status), ("transaction_not_found", 404))
        with self.assertRaises(hbank.AuthenticationError) as e:
            hbank.HBank("nope", base_url=self.base).list_subscriptions()
        self.assertEqual((e.exception.code, e.exception.status), ("invalid_api_key", 403))
        with self.assertRaises(hbank.HBankConnectionError):
            hbank.HBank("k", base_url="http://127.0.0.1:1", timeout=2).rate("EUR", "USD")

    def test_subscriptions(self):
        s = self.bank.create_subscription("9.99", "EUR", "month", description="Pro plan")
        self.assertEqual((s.status, s.amount, s.interval, s.interval_count), ("offered", Decimal("9.99"), "month", 1))
        self.assertIsNone(s.subscribed_at)
        self.assertEqual(self.bank.get_subscription(s.id).id, s.id)
        self.assertIn(s.id, [x.id for x in self.bank.list_subscriptions()])

        c = self.bank.checkout_subscription(s.id, callback_url="https://shop.example/cb")
        self.pay(c.transaction_id)
        self.assertEqual(self.bank.get_payment(c.transaction_id).subscription_id, s.id)
        active = self.bank.get_subscription(s.id)
        self.assertEqual(active.status, "active")
        self.assertEqual(active.subscribed_at.tzinfo, timezone.utc)
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.checkout_subscription(s.id)
        self.assertEqual(e.exception.code, "not_open")

        canceled = self.bank.cancel_subscription(s.id)
        self.assertTrue(canceled.canceled)
        self.assertEqual(canceled.canceled_by, "merchant")
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.cancel_subscription(s.id)
        self.assertEqual(e.exception.code, "already_canceled")

        one_call = self.bank.create_subscription_checkout(5, "EUR", "week", interval_count=2)
        self.assertEqual(one_call.subscription.interval_count, 2)
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.create_subscription(5, "EUR", "fortnight")
        self.assertEqual(e.exception.code, "invalid_interval")

    def test_several_subscriptions_in_one_checkout(self):
        offered = self.bank.create_subscription("5", "EUR", "month", description="Storage")
        c = self.bank.create_subscriptions_checkout(
            [offered.id, {"amount": "2.50", "currency": "EUR", "interval": "week", "description": "Support"}],
            callback_url="https://shop.example/cb")
        self.assertEqual([s.id for s in c.subscriptions][0], offered.id)
        self.assertEqual([s.description for s in c.subscriptions], ["Storage", "Support"])
        self.pay(c.transaction_id)
        payment = self.bank.get_payment(c.transaction_id)
        self.assertEqual(payment.amount, Decimal("7.50"))
        self.assertIsNone(payment.subscription_id)
        self.assertEqual(payment.subscription_ids, [s.id for s in c.subscriptions])
        self.assertTrue(all(self.bank.get_subscription(s.id).status == "active" for s in c.subscriptions))

        with self.assertRaises(hbank.HBankError) as e:
            self.bank.create_subscriptions_checkout([{"amount": 1, "currency": "EUR", "interval": "month"},
                                                     {"amount": 1, "currency": "USD", "interval": "month"}])
        self.assertEqual(e.exception.code, "mixed_currencies")
        with self.assertRaises(hbank.HBankError) as e:
            self.bank.create_subscriptions_checkout([offered.id])
        self.assertEqual(e.exception.code, "not_open")

    def test_currency(self):
        self.assertEqual(self.bank.convert(100, "EUR", "USD"), Decimal("108.37"))
        rate = self.bank.rate("EUR", "USD")
        self.assertEqual(rate.to_rate, Decimal("1.0837"))
        self.assertGreater(rate.from_rate, 0)


class CallbackTests(unittest.TestCase):
    def test_parse_and_answer(self):
        cb = hbank.parse_callback(json.dumps({"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 24.90, "currency": "EUR", "status": "completed",
                                              "description": "Order 1042"}))
        self.assertEqual((cb.id, cb.amount, cb.currency), ("tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", Decimal("24.9"), "EUR"))
        self.assertEqual(hbank.approve(), {"resume": True})
        self.assertEqual(hbank.refuse("Out of stock"), {"resume": False, "error": "Out of stock"})
        with self.assertRaises(hbank.HBankError):
            hbank.parse_callback(b"{}")

    def test_signature(self):
        body = '{"id":7310,"amount":24.9,"currency":"EUR","status":"awaiting_approval","description":"Order 1042"}'
        header = "t=1700000000,v1=fcfc30b9667c3a8e8aea68178c36716153e075f79c61521bf3586088d9877281"
        self.assertTrue(hbank.verify_signature("hbcb_test", header, body, now=1700000100))
        self.assertTrue(hbank.verify_signature("hbcb_test", header, body.encode(), now=1700000100))
        self.assertFalse(hbank.verify_signature("hbcb_other", header, body, now=1700000100))
        self.assertFalse(hbank.verify_signature("hbcb_test", header, body.replace("24.9", "0.1"), now=1700000100))
        self.assertFalse(hbank.verify_signature("hbcb_test", header, body, now=1700000400))  # too old
        self.assertFalse(hbank.verify_signature("hbcb_test", None, body))
        self.assertFalse(hbank.verify_signature("hbcb_test", "garbage", body))

    def test_dotnet_timestamps(self):
        t = _time("2026-10-03T09:12:44.1234567Z")
        self.assertEqual((t.microsecond, t.tzinfo), (123456, timezone.utc))
        self.assertEqual(_time("2026-10-03T09:12:44").tzinfo, timezone.utc)
        self.assertEqual(_time("2026-10-03T09:12:44+02:00").utcoffset().total_seconds(), 7200)


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