# myapp/utils.py
"""
توابع کمکی برای مدیریت رزرو و پرونده پزشکی
"""
import json
from .models import MedicalRecord, MedicalRecordEntry, ReservationChangeLog


def set_current_user_for_model(instance, user):
    """تنظیم کاربر فعلی برای مدل"""
    instance._current_user = user


def get_reservation_history(reservation_id):
    """دریافت تاریخچه تغییرات رزرو"""
    return ReservationChangeLog.objects.filter(
        reservation_id=reservation_id
    ).select_related('changed_by').order_by('-timestamp')


def create_medical_entry(medical_record, entry_type, title, content, user, doctor=None, technician=None):
    """ایجاد ورودی جدید در پرونده پزشکی"""
    return MedicalRecordEntry.objects.create(
        medical_record=medical_record,
        entry_type=entry_type,
        title=title,
        content=content,
        doctor=doctor,
        technician=technician,
        created_by=user
    )


def get_medical_record_entries(reservation_id, entry_type=None):
    """دریافت ورودی‌های پرونده پزشکی"""
    try:
        medical_record = MedicalRecord.objects.get(reservation_id=reservation_id)
        entries = medical_record.entries.all()

        if entry_type:
            entries = entries.filter(entry_type=entry_type)

        return entries.select_related('doctor', 'technician', 'created_by')
    except MedicalRecord.DoesNotExist:
        return MedicalRecordEntry.objects.none()


def add_doctor_note(reservation_id, title, content, doctor, user):
    """اضافه کردن یادداشت دکتر"""
    try:
        medical_record = MedicalRecord.objects.get(reservation_id=reservation_id)
        return create_medical_entry(
            medical_record=medical_record,
            entry_type='doctor_note',
            title=title,
            content=content,
            user=user,
            doctor=doctor
        )
    except MedicalRecord.DoesNotExist:
        raise ValueError("Medical record not found for this reservation")


def add_technician_note(reservation_id, title, content, technician, user):
    """اضافه کردن یادداشت تکنسین"""
    try:
        medical_record = MedicalRecord.objects.get(reservation_id=reservation_id)
        return create_medical_entry(
            medical_record=medical_record,
            entry_type='technician_note',
            title=title,
            content=content,
            user=user,
            technician=technician
        )
    except MedicalRecord.DoesNotExist:
        raise ValueError("Medical record not found for this reservation")


def add_prescription(reservation_id, title, content, doctor, user):
    """اضافه کردن نسخه"""
    try:
        medical_record = MedicalRecord.objects.get(reservation_id=reservation_id)
        return create_medical_entry(
            medical_record=medical_record,
            entry_type='prescription',
            title=title,
            content=content,
            user=user,
            doctor=doctor
        )
    except MedicalRecord.DoesNotExist:
        raise ValueError("Medical record not found for this reservation")


def get_reservation_summary(reservation_id):
    """خلاصه کامل رزرو شامل لاگ‌ها و پرونده پزشکی"""
    from .models import Reservation

    try:
        reservation = Reservation.objects.get(id=reservation_id)

        # تاریخچه تغییرات
        change_logs = get_reservation_history(reservation_id)

        # ورودی‌های پرونده پزشکی
        medical_entries = get_medical_record_entries(reservation_id)

        return {
            'reservation': reservation,
            'change_logs': change_logs,
            'medical_entries': medical_entries,
            'total_changes': change_logs.count(),
            'total_medical_entries': medical_entries.count()
        }
    except Reservation.DoesNotExist:
        return None


# -------------------------------------------------------------------
# myapp/services.py

from django.db import transaction
from .models import Reservation, MedicalRecord
from .utils import set_current_user_for_model, add_doctor_note


class ReservationService:

    @staticmethod
    def create_reservation_with_medical_record(reservation_data, user):
        with transaction.atomic():
            reservation = Reservation(**reservation_data)
            set_current_user_for_model(reservation, user)
            reservation.save()
            return reservation

    @staticmethod
    def update_reservation_status(reservation_id, new_status, user, description=None):
        reservation = Reservation.objects.get(id=reservation_id)
        old_status = reservation.status

        reservation.update_status(new_status, user)

        if description:
            add_doctor_note(
                reservation_id=reservation_id,
                title=f"Status Change: {old_status} → {new_status}",
                content=description,
                doctor=getattr(user, 'doctor', None),
                user=user
            )

        return reservation

    @staticmethod
    def complete_medical_examination(reservation_id, examination_data, doctor, user):
        """تکمیل معاینه پزشکی"""
        with transaction.atomic():
            medical_record = MedicalRecord.objects.get(reservation_id=reservation_id)

            # آپدیت فیلدهای پرونده پزشکی
            for field, value in examination_data.items():
                if hasattr(medical_record, field):
                    setattr(medical_record, field, value)

            medical_record.save()

            # اضافه کردن یادداشت معاینه
            add_doctor_note(
                reservation_id=reservation_id,
                title="Medical Examination Completed",
                content=f"Examination completed by Dr. {doctor.get_full_name()}",
                doctor=doctor,
                user=user
            )

            return medical_record


# -------------------------------------------------------------------
# myapp/managers.py (اختیاری)
"""
مدیرهای مخصوص برای کوئری‌های پیچیده
"""
from django.db import models