from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from api.property_api.category.models.category import Category
from api.property_api.property.models.property import Property
from api.property_api.property_nearby_facilities.models.property_nearby_facilities import PropertyNearbyFacilities
from common.exceptions.exceptions import custom_exception_handler


class PropertyNearbyFacilitiesAPITestCase(APITestCase):
    def setUp(self):
        self.category_1 = Category.objects.create(name="Hospital")
        self.property_1 = Property.objects.create(name="housing",address="ctg",per_sqr_ft_price=200.00,description="beautiful")
        self.facility_1 = PropertyNearbyFacilities.objects.create(categories=self.category_1,name="kfc",property_id=self.property_1,distance_meters=1500)
        self.list_url = reverse("property_nearby_facilities-list-create")
        self.detail_url = lambda pk: reverse("property_nearby_facilities-detail", kwargs={"pk": pk})

    def test_create_facility(self):
        data = {"name": "Restaurant","categories":"1","property_id":"1","distance_meters":"2000"}
        response = self.client.post(self.list_url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(PropertyNearbyFacilities.objects.filter(name="Restaurant").exists())

    def test_list_active_facilities(self):
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data["results"]), 1)  # only active

    def test_get_facility_detail(self):
        response = self.client.get(self.detail_url(self.facility_1.id))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["name"], self.facility_1.name)

    def test_get_invalid_facility_detail(self):
        response = self.client.get(self.detail_url(9999))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_facility_detail(self):
        data = {"name": "School","categories":self.category_1.id,"property_id":self.property_1.id,"distance_meters":"3000"}
        response = self.client.put(self.detail_url(self.facility_1.id), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.facility_1.refresh_from_db()
        self.assertEqual(self.facility_1.name, "School")

    def test_soft_delete_facility_details(self):
        response = self.client.delete(self.detail_url(self.facility_1.id))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.facility_1.refresh_from_db()
        self.assertFalse(self.facility_1.is_active)
