# Generated by Django 5.2 on 2025-09-26 17:59

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


def populate_created_by(apps, schema_editor):
    ApiKey = apps.get_model('api', 'ApiKey')
    ApiKey.objects.filter(created_by__isnull=True).update(created_by=F('user'))


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0143_organizationbilling_pending_seat_effective_at_and_more'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RemoveConstraint(
            model_name='apikey',
            name='unique_api_key_user_name',
        ),
        migrations.AddField(
            model_name='apikey',
            name='created_by',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_api_keys', to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='apikey',
            name='organization',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='api_keys', to='api.organization'),
        ),
        migrations.AlterField(
            model_name='apikey',
            name='user',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='api_keys', to=settings.AUTH_USER_MODEL),
        ),
        migrations.RunPython(populate_created_by, migrations.RunPython.noop),
        migrations.AddConstraint(
            model_name='apikey',
            constraint=models.UniqueConstraint(condition=models.Q(('organization__isnull', True), ('user__isnull', False)), fields=('user', 'name'), name='unique_api_key_user_name'),
        ),
        migrations.AddConstraint(
            model_name='apikey',
            constraint=models.UniqueConstraint(condition=models.Q(('organization__isnull', False)), fields=('organization', 'name'), name='unique_api_key_org_name'),
        ),
        migrations.AddConstraint(
            model_name='apikey',
            constraint=models.CheckConstraint(condition=models.Q(models.Q(('organization__isnull', True), ('user__isnull', False)), models.Q(('organization__isnull', False), ('user__isnull', True)), _connector='OR'), name='api_key_exactly_one_owner'),
        ),
    ]
