from django.db import connection, transaction

from apps.herd.models import Organization, Rancher, RancherOrganizationLink

BATCH_SIZE = 2000


def process_city(city_id):
    connection.close()

    orgs = Organization.objects.filter(
        city_id=city_id,
        type__key='CO'
    )

    if not orgs.exists() or orgs.count() > 1:
        return

    coop = orgs.first()

    ranchers = (
        Rancher.objects.filter(city_id=city_id)
        .only('id')
    )

    buffer = []

    for rancher in ranchers.iterator(chunk_size=BATCH_SIZE):

        if RancherOrganizationLink.objects.filter(
                rancher_id=rancher.id
        ).exists():
            continue

        buffer.append(
            RancherOrganizationLink(
                rancher_id=rancher.id,
                organization_id=coop.id
            )
        )

        if len(buffer) >= BATCH_SIZE:
            bulk_insert(buffer)
            buffer.clear()

    if buffer:
        bulk_insert(buffer)


@transaction.atomic
def bulk_insert(objs):
    RancherOrganizationLink.objects.bulk_create(
        objs,
        ignore_conflicts=True
    )
