from django.db import models


class LeveeWorkSession(models.Model):
    year = models.IntegerField(verbose_name='年度')
    date = models.DateField(verbose_name='畔塗日')
    title = models.CharField(max_length=100, default='水稲畔塗', verbose_name='タイトル')
    notes = models.TextField(blank=True, default='', verbose_name='備考')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = '畔塗記録'
        verbose_name_plural = '畔塗記録'
        ordering = ['-date', '-id']

    def __str__(self):
        return f'{self.date} {self.title}'


class LeveeWorkSessionItem(models.Model):
    session = models.ForeignKey(
        LeveeWorkSession,
        on_delete=models.CASCADE,
        related_name='items',
        verbose_name='畔塗記録',
    )
    field = models.ForeignKey(
        'fields.Field',
        on_delete=models.PROTECT,
        verbose_name='圃場',
    )
    plan = models.ForeignKey(
        'plans.Plan',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='+',
        verbose_name='作付け計画',
    )
    crop_name_snapshot = models.CharField(max_length=100, verbose_name='作物名スナップショット')
    variety_name_snapshot = models.CharField(
        max_length=100,
        blank=True,
        default='',
        verbose_name='品種名スナップショット',
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = '畔塗対象圃場'
        verbose_name_plural = '畔塗対象圃場'
        unique_together = [['session', 'field']]
        ordering = ['field__display_order', 'field__id']

    def __str__(self):
        return f'{self.session} / {self.field.name}'

