from django.contrib.auth import get_user_model
from scheduler.models import Resource, AppointmentType, AvailabilityRule, BlockedPeriod, ExceptionDay
from booking.models import Appointment
from django.db import transaction

User = get_user_model()

def run():
    print("🚀 Iniciando migración de Resources (Versión Corregida M2M)...\n")

    with transaction.atomic():
        for user in User.objects.all():
            print(f"👤 Procesando usuario: {user.email}")

            # 1. Crear Resource por defecto si no existe
            resource, created = Resource.objects.get_or_create(
                user=user,
                name="Principal",
                defaults={"is_active": True}
            )

            if created:
                print("   ✅ Resource 'Principal' creado")
            else:
                print("   ℹ️ Resource 'Principal' ya existía")

            # 2. Asociar AppointmentType sin resource (ManyToMany)
            at_to_update = AppointmentType.objects.filter(user=user, resources__isnull=True)
            at_count = at_to_update.count()
            for at in at_to_update:
                at.resources.add(resource)
            print(f"   🔧 AppointmentType actualizados: {at_count}")

            # 3. Asociar Appointment sin resource
            ap_updated = Appointment.objects.filter(
                user=user,
                resource__isnull=True
            ).update(resource=resource)
            print(f"   🔧 Appointments actualizadas: {ap_updated}")

            # 4. Asociar reglas sin resource
            ar_updated = AvailabilityRule.objects.filter(
                user=user,
                resource__isnull=True
            ).update(resource=resource)

            bp_updated = BlockedPeriod.objects.filter(
                user=user,
                resource__isnull=True
            ).update(resource=resource)

            ex_updated = ExceptionDay.objects.filter(
                user=user,
                resource__isnull=True
            ).update(resource=resource)

            print(f"   🔧 AvailabilityRules: {ar_updated}")
            print(f"   🔧 BlockedPeriods: {bp_updated}")
            print(f"   🔧 ExceptionDays: {ex_updated}")

            print("")

    print("✅ Migración completada correctamente")

if __name__ == "__main__":
    run()
