from asgiref.sync import sync_to_async
from django.db import connections
from datetime import datetime, timedelta
from hotels.models import Reservation, Hotel, FraudLog


async def detect_fraud(hotel_id, period="day"):
    """
    Сравнивает данные из PMS и QR базы для обнаружения FRAUD-действий.
    :param hotel_id: ID отеля для анализа.
    :param period: Период времени для анализа (day, week, month).
    """
    now = datetime.now()
    if period == "day":
        start_date = now - timedelta(days=1)
    elif period == "week":
        start_date = now - timedelta(weeks=1)
    elif period == "month":
        start_date = now - timedelta(days=30)
    else:
        start_date = None

    end_date = now

    # Данные из PMS
    reservations = await sync_to_async(list)(
        Reservation.objects.filter(
            hotel_id=hotel_id,
            check_in__date__range=(start_date, end_date)
        )
    )

    # Данные из QR-системы
    qr_checkins = []
    with connections['wordpress'].cursor() as cursor:
        cursor.execute(
            "SELECT reservation_id, guest_name, check_in_date FROM qr_checkins WHERE check_in_date BETWEEN %s AND %s",
            [start_date, end_date]
        )
        qr_checkins = cursor.fetchall()

    qr_checkins_set = {row[0] for row in qr_checkins}  # Множество reservation_id

    # Сравнение данных
    for res in reservations:
        if res.id not in qr_checkins_set:
            # Записываем FRAUD
            await sync_to_async(FraudLog.objects.create)(
                hotel_id=hotel_id,
                reservation_id=res.id,
                guest_name=res.guest_name,
                check_in_date=res.check_in.date(),
                message="Проверка на QR-систему провалилась."
            )
