from django.test import TransactionTestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from unittest.mock import patch
from django.contrib.auth import get_user_model
from hotel.models import Hotel, RoomType, HotelBooking
from payments.models import Payment
from django.contrib.contenttypes.models import ContentType
from datetime import date, timedelta

User = get_user_model()

class PMSIntegrationTest(TransactionTestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username='testuser', password='password')
        self.hotel = Hotel.objects.create(owner=self.user, name='Test Hotel', city='Test City', address='Test Address')
        self.room_type = RoomType.objects.create(hotel=self.hotel, name='Deluxe', price=1000, total_rooms=10)
        
        self.booking = HotelBooking.objects.create(
            user=self.user,
            hotel=self.hotel,
            branch='Main',
            room_type=self.room_type,
            check_in=date.today(),
            check_out=date.today() + timedelta(days=1),
            rooms_booked=1,
            status='pending'
        )
        
        self.payment = Payment.objects.create(
            content_type=ContentType.objects.get_for_model(HotelBooking),
            object_id=self.booking.id,
            amount=self.booking.total_amount,
            transaction_id='ORDER123',
            payment_method='Paytm-Mock',
            status='pending'
        )
        
        self.callback_url = reverse('payment-callback') # Adjust if generic view name is different

    @patch('payments.utils.PaytmMock.verify_checksum')
    @patch('hotel.pms_integration.PMSService.send_booking')
    def test_pms_sync_on_successful_payment(self, mock_send_booking, mock_verify_checksum):
        # Mocking checksum verification to be True
        mock_verify_checksum.return_value = True
        
        payload = {
            'ORDER_ID': 'ORDER123',
            'RESPCODE': '01',
            'CHECKSUMHASH': 'valid_checksum'
        }
        
        # We need to find the correct URL name. Based on views.py it is likely in urls.py
        # The URL in hotelfinder/urls.py is 'api/payment/'
        response = self.client.post('/api/payment/callback/', payload)
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        
        # Refresh booking from DB
        self.booking.refresh_from_db()
        self.assertEqual(self.booking.status, 'confirmed')
        
        # Verify PMS service was called
        mock_send_booking.assert_called_once_with(self.booking)
