from django.conf import settings
from django.db import models


class ContactGroup(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.CharField(max_length=255, blank=True)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class Contact(models.Model):
    class ContactType(models.TextChoices):
        INDIVIDUAL = "individual", "Individual"
        ORGANISATION = "organisation", "Organisation"

    contact_type = models.CharField(
        max_length=16, choices=ContactType.choices, default=ContactType.INDIVIDUAL
    )
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    organisation_name = models.CharField(max_length=255, blank=True)
    job_title = models.CharField(max_length=150, blank=True)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=32, blank=True)
    country = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100, blank=True)
    address = models.TextField(blank=True)
    website = models.URLField(blank=True)
    groups = models.ManyToManyField(ContactGroup, blank=True, related_name="contacts")
    notes = models.TextField(blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="contacts_created",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["last_name", "first_name", "organisation_name"]

    def __str__(self):
        if self.contact_type == self.ContactType.ORGANISATION:
            return self.organisation_name or "Unnamed organisation"
        name = f"{self.first_name} {self.last_name}".strip()
        return name or self.email or "Unnamed contact"

    @property
    def display_name(self) -> str:
        return str(self)
