# Migration: add MentorStudentConnection, migrate data from MentorshipRequest and MentorClientInvitation

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


def migrate_to_mentor_student_connection(apps, schema_editor):
    """Migrate MentorshipRequest and MentorClientInvitation to MentorStudentConnection."""
    MentorStudentConnection = apps.get_model('users', 'MentorStudentConnection')
    MentorshipRequest = apps.get_model('users', 'MentorshipRequest')
    MentorClientInvitation = apps.get_model('users', 'MentorClientInvitation')
    Client = apps.get_model('users', 'Client')

    # Map (mentor_id, student_id) -> connection to avoid duplicates
    created_pairs = set()

    # 1. Migrate MentorClientInvitation (mentor-initiated)
    for inv in MentorClientInvitation.objects.all():
        key = (inv.mentor_id, inv.student_id)
        if key in created_pairs:
            continue
        # Map invitation status to connection status
        if inv.status == 'pending':
            status = 'pending_student'
        elif inv.status == 'student_confirmed':
            try:
                client = Client.objects.get(user_id=inv.student_id)
                if client.parents.exists():
                    status = 'pending_parent'
                else:
                    status = 'accepted'
            except Client.DoesNotExist:
                status = 'accepted'
        elif inv.status in ('parent_confirmed', 'confirmed'):
            status = 'accepted'
        elif inv.status == 'rejected':
            status = 'rejected'
        else:
            status = 'pending_student'

        MentorStudentConnection.objects.create(
            mentor_id=inv.mentor_id,
            student_id=inv.student_id,
            status=status,
            initiator='mentor',
            student_confirmed_at=inv.student_confirmed_at,
            parent_confirmed_at=inv.parent_confirmed_at,
            confirm_token=inv.confirm_token,
            created_at=inv.created_at,
            updated_at=inv.updated_at,
        )
        created_pairs.add(key)

    # 2. Migrate MentorshipRequest (student-initiated), skip if pair already exists
    for req in MentorshipRequest.objects.all():
        key = (req.mentor_id, req.student_id)
        if key in created_pairs:
            continue
        status_map = {'pending': 'pending_mentor', 'accepted': 'accepted', 'rejected': 'rejected'}
        status = status_map.get(req.status, 'pending_mentor')

        MentorStudentConnection.objects.create(
            mentor_id=req.mentor_id,
            student_id=req.student_id,
            status=status,
            initiator='student',
            created_at=req.created_at,
            updated_at=req.updated_at,
        )
        created_pairs.add(key)


def reverse_migrate(apps, schema_editor):
    """Reverse: cannot restore old tables from MentorStudentConnection (data loss)."""
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0006_mentorshiprequest'),
    ]

    operations = [
        migrations.CreateModel(
            name='MentorStudentConnection',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('status', models.CharField(
                    choices=[
                        ('pending_mentor', 'Ожидает ответа ментора'),
                        ('pending_student', 'Ожидает подтверждения студента'),
                        ('pending_parent', 'Ожидает подтверждения родителя'),
                        ('accepted', 'Принято'),
                        ('rejected', 'Отклонено'),
                    ],
                    db_index=True,
                    max_length=20,
                    verbose_name='Статус',
                )),
                ('initiator', models.CharField(
                    choices=[('student', 'Студент'), ('mentor', 'Ментор')],
                    max_length=10,
                    verbose_name='Инициатор',
                )),
                ('student_confirmed_at', models.DateTimeField(blank=True, null=True, verbose_name='Подтверждено студентом')),
                ('parent_confirmed_at', models.DateTimeField(blank=True, null=True, verbose_name='Подтверждено родителем')),
                ('confirm_token', models.CharField(
                    blank=True,
                    max_length=64,
                    null=True,
                    unique=True,
                    verbose_name='Токен подтверждения',
                )),
                ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')),
                ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Дата обновления')),
                ('mentor', models.ForeignKey(
                    limit_choices_to={'role': 'mentor'},
                    on_delete=django.db.models.deletion.CASCADE,
                    related_name='connections_as_mentor',
                    to=settings.AUTH_USER_MODEL,
                    verbose_name='Ментор',
                )),
                ('student', models.ForeignKey(
                    limit_choices_to={'role': 'client'},
                    on_delete=django.db.models.deletion.CASCADE,
                    related_name='connections_as_student',
                    to=settings.AUTH_USER_MODEL,
                    verbose_name='Студент',
                )),
            ],
            options={
                'verbose_name': 'Связь ментор—студент',
                'verbose_name_plural': 'Связи ментор—студент',
                'db_table': 'mentor_student_connections',
                'ordering': ['-created_at'],
                'unique_together': {('mentor', 'student')},
            },
        ),
        migrations.AddIndex(
            model_name='mentorstudentconnection',
            index=models.Index(fields=['status'], name='ment_stu_con_status_idx'),
        ),
        migrations.AddIndex(
            model_name='mentorstudentconnection',
            index=models.Index(fields=['mentor', 'status'], name='ment_stu_con_mentor_status_idx'),
        ),
        migrations.AddIndex(
            model_name='mentorstudentconnection',
            index=models.Index(fields=['student', 'status'], name='ment_stu_con_student_status_idx'),
        ),
        migrations.AddIndex(
            model_name='mentorstudentconnection',
            index=models.Index(fields=['confirm_token'], name='ment_stu_con_confirm_token_idx'),
        ),
        migrations.RunPython(migrate_to_mentor_student_connection, reverse_migrate),
    ]
