# B2B (multi-company) isolation tests for the Insurance admin API.
#   python manage.py test Insurance.tests_b2b
from django.test import TestCase
from django.urls import resolve
from rest_framework.test import APIClient

from Company.models import company_details
from Insurance.models import InsuranceTPA, NetworkHospital

B = "/api/insurance/"


def mk_company(tag, n):
    return company_details.objects.create(
        email=f"{tag}@x.com", password="x", contact_no=f"93{n:08d}", status=True,
        is_verified=True, Registered_Company_Name=f"Co {tag}", Company_address="Pune")


def cl(company):
    c = APIClient()
    c.force_authenticate(user=company)
    return c


class InsuranceB2BIsolation(TestCase):
    def setUp(self):
        self.a_co, self.b_co = mk_company("ins-a", 1), mk_company("ins-b", 2)
        self.a, self.b = cl(self.a_co), cl(self.b_co)

    def _tpa(self, c, name="Medi Assist"):
        r = c.post(B + "tpa/", {"name": name}, format="json")
        self.assertIn(r.status_code, (200, 201), r.content)
        return r.json().get("id") or r.json()["data"]["id"]

    def test_lists_are_company_scoped(self):
        self._tpa(self.a)
        for res in ("tpa/", "hospitals/", "policies/", "dependents/", "claims/"):
            body = self.b.get(B + res).json()
            rows = body["results"] if isinstance(body, dict) and "results" in body else body
            self.assertEqual(len(rows), 0, res)

    def test_other_company_cannot_read_update_delete(self):
        pk = self._tpa(self.a)
        self.assertEqual(self.b.get(f"{B}tpa/{pk}/").status_code, 404)
        self.assertEqual(self.b.patch(f"{B}tpa/{pk}/", {"name": "Hacked"}, format="json").status_code, 404)
        self.assertEqual(self.b.delete(f"{B}tpa/{pk}/").status_code, 404)
        self.assertEqual(InsuranceTPA.objects.get(pk=pk).name, "Medi Assist")
        self.assertEqual(self.a.get(f"{B}tpa/{pk}/").status_code, 200)

    def test_company_cannot_be_spoofed_on_create(self):
        r = self.b.post(B + "tpa/", {"name": "Spoof", "company": self.a_co.pk}, format="json")
        self.assertIn(r.status_code, (200, 201), r.content)
        self.assertEqual(InsuranceTPA.objects.get(name="Spoof").company_id, self.b_co.pk)

    def test_same_name_allowed_across_companies(self):
        self._tpa(self.a, "Paramount")
        self._tpa(self.b, "Paramount")
        self.assertEqual(InsuranceTPA.objects.filter(name="Paramount").count(), 2)

    def test_hospitals_isolated(self):
        r = self.a.post(B + "hospitals/", {"hospital_name": "Ruby Hall", "city": "Pune"}, format="json")
        self.assertIn(r.status_code, (200, 201), r.content)
        self.assertEqual(NetworkHospital.objects.filter(company=self.a_co).count(), 1)
        body = self.b.get(B + "hospitals/").json()
        rows = body["results"] if isinstance(body, dict) and "results" in body else body
        self.assertEqual(rows, [])

    def test_employee_side_insurance_is_mounted(self):
        # employee insurance is served by the Employee app (Employee/urls.py)
        self.assertTrue(resolve("/employee/insurance/"))
