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.property.models.property import Property
from common.exceptions.exceptions import custom_exception_handler


class PropertyAPITestCase(APITestCase):
    def setUp(self):
        self.property_1 = Property.objects.create(name="housing",address="ctg",per_sqr_ft_price=200.00,description="beautiful")
        self.list_url = reverse("properties-list-create")
        self.exist_url = lambda name: reverse("properties-exist", kwargs={"name": name})
        self.detail_url = lambda pk: reverse("properties-detail", kwargs={"pk": pk})

    def test_create_property(self):
        data = {"name": "macdonald","address":"Dhaka","per_sqr_ft_price":"500.00","description":"nice"}
        response = self.client.post(self.list_url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(Property.objects.filter(name="macdonald").exists())

    def test_list_active_properties(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_property_detail(self):
        response = self.client.get(self.detail_url(self.property_1.id))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["name"], self.property_1.name)

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

    def test_update_property(self):
        data = {"name": "KFC1","address":"ctg","per_sqr_ft_price":"200.00","description":"beautiful"}
        response = self.client.put(self.detail_url(self.property_1.id), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.property_1.refresh_from_db()
        self.assertEqual(self.property_1.name, "KFC1")

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

    def test_property_exist_true(self):
        response = self.client.get(self.exist_url("housing"))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data["isExist"])

    def test_property_exist_false(self):
        response = self.client.get(self.exist_url("nonexistent"))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertFalse(response.data["isExist"])

    def test_property_exist_blank(self):
        response = self.client.get(self.exist_url(" "))
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)