from __future__ import annotations

import sys
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from brightree import Brightree
from brightree.config import DEFAULT_SERVICES
from brightree.helpers import ArrayHelper
from brightree.services import (
    CustomField,
    Doctor,
    Document,
    Documentation,
    Insurance,
    Inventory,
    Invoice,
    Patient,
    Pickup,
    Pricing,
    Reference,
    SalesOrder,
    Security,
)


class ClientTest(unittest.TestCase):
    def setUp(self) -> None:
        self.client = Brightree("Username", "Password")

    def test_service_accessors(self) -> None:
        self.assertIsInstance(self.client.Patient(), Patient)
        self.assertIsInstance(self.client.Doctor(), Doctor)
        self.assertIsInstance(self.client.CustomField(), CustomField)
        self.assertIsInstance(self.client.Pickup(), Pickup)
        self.assertIsInstance(self.client.SalesOrder(), SalesOrder)
        self.assertIsInstance(self.client.Pricing(), Pricing)
        self.assertIsInstance(self.client.Security(), Security)
        self.assertIsInstance(self.client.Documentation(), Documentation)
        self.assertIsInstance(self.client.Document(), Document)
        self.assertIsInstance(self.client.Insurance(), Insurance)
        self.assertIsInstance(self.client.Inventory(), Inventory)
        self.assertIsInstance(self.client.Reference(), Reference)
        self.assertIsInstance(self.client.Invoice(), Invoice)

    def test_array_helper_builds_expected_payload(self) -> None:
        helper = ArrayHelper()
        payload = helper.search({"SearchParams": {"Branch": {"Value": 102}}}).sort().page(2).pageSize(25).build()
        self.assertEqual(
            payload,
            {
                "SearchParams": {"Branch": {"Value": 102}},
                "SortParams": [],
                "page": 2,
                "pageSize": 25,
            },
        )

    def test_client_merges_partial_service_config_with_defaults(self) -> None:
        custom_patient_url = "https://example.com/patient"
        client = Brightree(
            "Username",
            "Password",
            config={"service": {"patient": custom_patient_url}, "timeout": 30},
        )

        self.assertEqual(client.info["config"]["service"]["patient"], custom_patient_url)
        self.assertEqual(client.info["config"]["service"]["doctor"], DEFAULT_SERVICES["doctor"])
        self.assertEqual(client.info["config"]["timeout"], 30)


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