from django.db import transaction

from .models import RiceTransplantEntry, RiceTransplantPlan


@transaction.atomic
def move_rice_transplant_entries_for_variety_change(change):
    old_variety_id = change.old_variety_id
    new_variety = change.new_variety
    if old_variety_id is None or new_variety is None:
        return 0

    old_plans = (
        RiceTransplantPlan.objects
        .filter(
            year=change.year,
            variety_id=old_variety_id,
            entries__field_id=change.field_id,
        )
        .distinct()
        .prefetch_related('entries')
    )

    moved_count = 0
    for old_plan in old_plans:
        entries_to_move = list(
            old_plan.entries.filter(field_id=change.field_id).order_by('id')
        )
        if not entries_to_move:
            continue

        new_plan = RiceTransplantPlan.objects.create(
            name=f'{change.year}年度 {new_variety.name} 田植え計画（品種変更移動）',
            year=change.year,
            variety=new_variety,
            default_seed_grams_per_box=old_plan.default_seed_grams_per_box,
            seedling_boxes_per_tan=old_plan.seedling_boxes_per_tan,
            notes=old_plan.notes,
        )

        RiceTransplantEntry.objects.filter(
            id__in=[entry.id for entry in entries_to_move]
        ).update(plan=new_plan)
        moved_count += len(entries_to_move)

    return moved_count
