from .models import WorkRecord


def sync_delivery_work_record(trip):
    if trip.date is None:
        WorkRecord.objects.filter(delivery_trip=trip).delete()
        return

    WorkRecord.objects.update_or_create(
        delivery_trip=trip,
        defaults={
            'work_date': trip.date,
            'work_type': WorkRecord.WorkType.FERTILIZER_DELIVERY,
            'title': f'肥料運搬: {trip.delivery_plan.name} {trip.order + 1}回目',
            'year': trip.delivery_plan.year,
            'auto_created': True,
            'spreading_session': None,
        },
    )


def sync_spreading_work_record(session):
    WorkRecord.objects.update_or_create(
        spreading_session=session,
        defaults={
            'work_date': session.date,
            'work_type': WorkRecord.WorkType.FERTILIZER_SPREADING,
            'title': f'肥料散布: {session.name.strip() or session.date}',
            'year': session.year,
            'auto_created': True,
            'delivery_trip': None,
        },
    )


def sync_levee_work_record(session):
    WorkRecord.objects.update_or_create(
        levee_work_session=session,
        defaults={
            'work_date': session.date,
            'work_type': WorkRecord.WorkType.LEVEE_WORK,
            'title': session.title,
            'year': session.year,
            'auto_created': True,
            'delivery_trip': None,
            'spreading_session': None,
        },
    )
