from django.db import migrations, models


def backfill_application_method(apps, schema_editor):
    Job = apps.get_model('jobs', 'Job')
    Company = apps.get_model('companies', 'Company')
    for job in Job.objects.all().iterator():
        company = None
        if job.posted_by_id:
            company = Company.objects.filter(owner_id=job.posted_by_id).first()
        if company and company.application_delivery_method == 'ats':
            job.application_method = 'ats'
            job.save(update_fields=['application_method'])


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0017_job_positions'),
        ('companies', '0005_company_application_delivery_method'),
    ]

    operations = [
        migrations.AddField(
            model_name='job',
            name='application_method',
            field=models.CharField(
                choices=[
                    ('ats', 'Apply through PezaJob'),
                    ('email', 'Apply through an external website/email'),
                ],
                default='email',
                help_text='How candidates should submit applications for this job.',
                max_length=10,
            ),
        ),
        migrations.RunPython(backfill_application_method, migrations.RunPython.noop),
    ]
