# Generated manually for issue #14

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


def migrate_user_profiles(apps, schema_editor):
    User = apps.get_model("auth", "User")
    UserProfile = apps.get_model("financial", "UserProfile")
    Employee = apps.get_model("financial", "Employee")
    TimeCardCell = apps.get_model("financial", "TimeCardCell")

    employee_user_ids = set(
        TimeCardCell.objects.values_list("timeCard__employee__user_id", flat=True)
    )

    for user in User.objects.all():
        if user.id in employee_user_ids:
            UserProfile.objects.update_or_create(
                user_id=user.id,
                defaults={"user_type": "employee"},
            )
        else:
            UserProfile.objects.update_or_create(
                user_id=user.id,
                defaults={"user_type": "client"},
            )
            Employee.objects.filter(user_id=user.id).delete()


def reverse_migrate_user_profiles(apps, schema_editor):
    User = apps.get_model("auth", "User")
    Employee = apps.get_model("financial", "Employee")

    for user in User.objects.all():
        Employee.objects.get_or_create(user_id=user.id)


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("financial", "0014_chargenumber_name"),
    ]

    operations = [
        migrations.CreateModel(
            name="UserProfile",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "user_type",
                    models.CharField(
                        choices=[("employee", "Employee"), ("client", "Client")],
                        default="client",
                        max_length=10,
                    ),
                ),
                (
                    "user",
                    models.OneToOneField(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="profile",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
        ),
        migrations.RunPython(migrate_user_profiles, reverse_migrate_user_profiles),
    ]
