# Generated by Django 4.2.1 on 2023-06-11 21:27

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


def copy_shared_secrets_data(apps, schema_editor):
    secret_model = apps.get_model('secrets', 'Secret')
    shared_secret_data_model = apps.get_model('secrets', 'SharedSecretData')

    secret_data = secret_model.objects.all().only(
        'id',
        'allowed_users',
        'allowed_groups'
    )

    user_shares = []
    group_shares = []
    for secret in secret_data:
        group_shares += [(secret, group) for group in secret.allowed_groups.all()]
        user_shares += [(secret, user) for user in secret.allowed_users.all()]

    shared_secret_data_model.objects.bulk_create(
        [shared_secret_data_model(secret=secret, user=user) for secret, user in user_shares] +
        [shared_secret_data_model(secret=secret, group=group) for secret, group in group_shares]
    )


class Migration(migrations.Migration):
    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('auth', '0012_alter_user_first_name_max_length'),
        ('secrets', '0025_alter_secret_description_alter_secret_name'),
    ]

    operations = [
        migrations.CreateModel(
            name='SharedSecretData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('group', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='auth.group')),
                ('secret', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='secrets.secret')),
                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'unique_together': {('user', 'secret'), ('group', 'secret')},
            },
        ),
        migrations.RunPython(
            code=copy_shared_secrets_data,
        ),
        migrations.RemoveField(
            model_name='secret',
            name='allowed_groups',
        ),
        migrations.RemoveField(
            model_name='secret',
            name='allowed_users',
        ),
        migrations.AddField(
            model_name='secret',
            name='allowed_groups',
            field=models.ManyToManyField(blank=True, related_name='allowed_passwords', through='secrets.SharedSecretData', to='auth.group'),
        ),
        migrations.AddField(
            model_name='secret',
            name='allowed_users',
            field=models.ManyToManyField(blank=True, related_name='allowed_passwords', through='secrets.SharedSecretData', to=settings.AUTH_USER_MODEL),
        ),
    ]
