from users.models import User
from hotels.models import Hotel, Reservation, UserHotel
from asgiref.sync import sync_to_async
from django.core.exceptions import ObjectDoesNotExist

async def get_user_from_chat_id(chat_id):
    try:
        return await sync_to_async(User.objects.get)(chat_id=chat_id)
    except ObjectDoesNotExist:
        return None

async def get_hotel_by_id(hotel_id):
    try:
        return await sync_to_async(Hotel.objects.get)(id=hotel_id)
    except ObjectDoesNotExist:
        return None

async def get_hotel_by_name(hotel_name):
    try:
        return await sync_to_async(Hotel.objects.get)(name=hotel_name)
    except ObjectDoesNotExist:
        return None
    
async def get_hotels_for_user(user):
    """Получение отелей, связанных с пользователем."""
    return await sync_to_async(list)(
        UserHotel.objects.filter(user=user).select_related('hotel')
    )


async def get_reservations(hotel_id, start_date=None, end_date=None):
    query = Reservation.objects.filter(hotel_id=hotel_id)
    if start_date:
        query = query.filter(check_in__gte=start_date)
    if end_date:
        query = query.filter(check_out__lte=end_date)
    return await sync_to_async(list)(query.prefetch_related('guests'))

def save_reservations(data):
    """
    Сохранение данных бронирований в базу данных.
    :param data: Список бронирований.
    """
    for booking in data:
        Reservation.objects.update_or_create(
            external_id=booking['id'],
            defaults={
                'check_in': booking['begin_date'],
                'check_out': booking['end_date'],
                'amount': booking['amount'],
                'notes': booking.get('notes', ''),
                'guest_name': booking['client']['fio'],
                'guest_phone': booking['client']['phone'],
            },
        )