# Generated by Django 5.1.12 on 2025-09-28 20:30


import django.db.models.deletion
import django.db.models.functions.datetime
from django.db import migrations, models

import lamindb.base.fields
import lamindb.base.users
import lamindb.models.run
import lamindb.models.sqlrecord


def migrate_person_to_record(apps, schema_editor):
    """Migrate Person to Record."""
    Person = apps.get_model("lamindb", "Person")
    if not Person.objects.exists():
        return  # No Person records to migrate

    with schema_editor.connection.cursor() as cursor:
        cursor.execute("""
            INSERT INTO lamindb_record (
                uid, name, created_at, updated_at, created_by_id, run_id, is_type
            )
            SELECT
                CONCAT(uid, uid) as uid,
                name,
                created_at,
                updated_at,
                created_by_id,
                run_id,
                False
            FROM lamindb_person
        """)

        migrated_count = cursor.rowcount
        print(f"\nMigrated {migrated_count} Person records to Record table")

    with schema_editor.connection.cursor() as cursor:
        cursor.execute("""
            INSERT INTO lamindb_referencerecord (
                created_at, created_by_id, feature_id, record_id, reference_id, run_id
            )
            SELECT
                NOW() as created_at,
                r.created_by_id,
                NULL as feature_id,
                rec.id as record_id,
                ra.reference_id,
                rec.run_id
            FROM lamindb_reference_authors ra
            JOIN lamindb_reference r ON ra.reference_id = r.id
            JOIN lamindb_person p ON ra.person_id = p.id
            JOIN lamindb_record rec ON rec.name = p.name
        """)

        created_count = cursor.rowcount
        print(f"\nCreated {created_count} ReferenceRecord links for migrated authors")


class Migration(migrations.Migration):
    dependencies = [
        ("lamindb", "0121_recorduser"),
    ]

    operations = [
        migrations.CreateModel(
            name="ReferenceRecord",
            fields=[
                (
                    "created_at",
                    lamindb.base.fields.DateTimeField(
                        blank=True,
                        db_default=django.db.models.functions.datetime.Now(),
                        db_index=True,
                        editable=False,
                    ),
                ),
                ("id", models.BigAutoField(primary_key=True, serialize=False)),
                (
                    "created_by",
                    lamindb.base.fields.ForeignKey(
                        blank=True,
                        default=lamindb.base.users.current_user_id,
                        editable=False,
                        on_delete=django.db.models.deletion.PROTECT,
                        related_name="+",
                        to="lamindb.user",
                    ),
                ),
                (
                    "feature",
                    lamindb.base.fields.ForeignKey(
                        blank=True,
                        default=None,
                        null=True,
                        on_delete=django.db.models.deletion.PROTECT,
                        related_name="links_referencerecord",
                        to="lamindb.feature",
                    ),
                ),
                (
                    "record",
                    lamindb.base.fields.ForeignKey(
                        blank=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="links_reference",
                        to="lamindb.record",
                    ),
                ),
                (
                    "reference",
                    lamindb.base.fields.ForeignKey(
                        blank=True,
                        on_delete=django.db.models.deletion.PROTECT,
                        related_name="links_record",
                        to="lamindb.reference",
                    ),
                ),
                (
                    "run",
                    lamindb.base.fields.ForeignKey(
                        blank=True,
                        default=lamindb.models.run.current_run,
                        null=True,
                        on_delete=django.db.models.deletion.PROTECT,
                        related_name="+",
                        to="lamindb.run",
                    ),
                ),
            ],
            options={
                "unique_together": {("reference", "feature", "record")},
            },
            bases=(lamindb.models.sqlrecord.IsLink, models.Model),
        ),
        migrations.AddField(
            model_name="reference",
            name="records",
            field=models.ManyToManyField(
                related_name="references",
                through="lamindb.ReferenceRecord",
                to="lamindb.record",
            ),
        ),
        migrations.RunPython(migrate_person_to_record),
        migrations.RemoveField(
            model_name="project",
            name="people",
        ),
        migrations.RemoveField(
            model_name="reference",
            name="authors",
        ),
        migrations.AlterUniqueTogether(
            name="personproject",
            unique_together=None,
        ),
        migrations.AlterUniqueTogether(
            name="recordperson",
            unique_together=None,
        ),
        migrations.RenameField(
            model_name="reference",
            old_name="records",
            new_name="linked_in_records",
        ),
        migrations.AddField(
            model_name="project",
            name="description",
            field=lamindb.base.fields.TextField(blank=True, default=None, null=True),
        ),
        migrations.AlterField(
            model_name="reference",
            name="description",
            field=lamindb.base.fields.TextField(blank=True, default=None, null=True),
        ),
        migrations.DeleteModel(
            name="Person",
        ),
        migrations.DeleteModel(
            name="PersonProject",
        ),
        migrations.DeleteModel(
            name="RecordPerson",
        ),
        migrations.AlterField(
            model_name="recordreference",
            name="value",
            field=lamindb.base.fields.ForeignKey(
                blank=True,
                on_delete=django.db.models.deletion.PROTECT,
                related_name="links_in_record",
                to="lamindb.reference",
            ),
        ),
        migrations.AlterUniqueTogether(
            name="projectrecord",
            unique_together={("project", "feature", "record")},
        ),
        migrations.AddField(
            model_name="reference",
            name="records",
            field=models.ManyToManyField(
                related_name="references",
                through="lamindb.ReferenceRecord",
                to="lamindb.record",
            ),
        ),
        migrations.AlterField(
            model_name="reference",
            name="linked_in_records",
            field=models.ManyToManyField(
                related_name="linked_references",
                through="lamindb.RecordReference",
                to="lamindb.record",
            ),
        ),
    ]
