from django.conf import settings
from django.db import models
from django.utils import timezone

from .constants import ACTIVITY_TYPES, OUTCOMES, PRIORITIES, STAGES, SYSTEM_TYPES


class Lead(models.Model):
    """The sales status of one school. Created the first time someone works on it."""
    school = models.OneToOneField("schools.School", on_delete=models.CASCADE, related_name="lead")
    stage = models.CharField(max_length=12, choices=STAGES, default="new", db_index=True)
    priority = models.CharField(max_length=8, choices=PRIORITIES, blank=True, default="", db_index=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                              on_delete=models.SET_NULL, related_name="leads")
    last_contacted_at = models.DateTimeField(null=True, blank=True)
    attempts = models.PositiveIntegerField(default=0)
    next_followup = models.DateField(null=True, blank=True, db_index=True)
    next_action = models.CharField(max_length=200, blank=True)
    deal_value = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    lost_reason = models.CharField(max_length=200, blank=True)
    stage_changed_at = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def contacted(self):
        return self.last_contacted_at is not None

    def __str__(self):
        return f"{self.school.name} [{self.stage}]"


class Activity(models.Model):
    """One entry in a school's timeline: a call, visit, note, or an automatic change record."""
    lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name="activities")
    kind = models.CharField(max_length=10, choices=ACTIVITY_TYPES + SYSTEM_TYPES)
    outcome = models.CharField(max_length=16, choices=OUTCOMES, blank=True)
    notes = models.TextField(blank=True)
    occurred_at = models.DateTimeField(default=timezone.now, db_index=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name="crm_activities")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-occurred_at", "-id"]
        verbose_name_plural = "activities"

    @property
    def is_system(self):
        return self.kind in ("stage", "system")

    def __str__(self):
        return f"{self.kind} on {self.lead.school.name}"


class Contact(models.Model):
    """A person at the school (the head teacher, an accountant, an IT teacher ...)."""
    school = models.ForeignKey("schools.School", on_delete=models.CASCADE, related_name="people")
    name = models.CharField(max_length=150)
    role = models.CharField(max_length=100, blank=True)
    phone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    is_primary = models.BooleanField(default=False, verbose_name="Main contact")

    class Meta:
        ordering = ["-is_primary", "name"]

    def __str__(self):
        return f"{self.name} ({self.school.name})"
