from django.db import models

class Region(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True, blank=True, null=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

class Constituency(models.Model):
    region = models.ForeignKey(Region, on_delete=models.CASCADE, related_name='constituencies')
    name = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.name} ({self.region.name})"

    class Meta:
        ordering = ['region', 'name']
        verbose_name_plural = "Constituencies"

class Farmer(models.Model):
    name = models.CharField(max_length=200)
    id_number = models.CharField(max_length=50, unique=True, verbose_name="National ID/Passport")
    phone_number = models.CharField(max_length=20, blank=True)
    constituency = models.ForeignKey(Constituency, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class AgriculturalHolding(models.Model):
    HOLDING_TYPES = [
        ('CROP', 'Crop Production'),
        ('LIVESTOCK', 'Livestock Production'),
        ('MIXED', 'Mixed Farming'),
        ('FISHERIES', 'Fisheries/Aquaculture'),
        ('FORESTRY', 'Forestry'),
    ]
    farmer = models.ForeignKey(Farmer, on_delete=models.CASCADE, related_name='holdings')
    size_hectares = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="Size (Hectares)")
    primary_activity = models.CharField(max_length=20, choices=HOLDING_TYPES)
    location_description = models.TextField(blank=True)

    def __str__(self):
        return f"{self.get_primary_activity_display()} - {self.farmer.name}"