from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import uuid

User = get_user_model()

class EventType(models.TextChoices):
    MAILING = 'MAIL', 'Mailing List'
    SMS = 'SMS', 'SMS Campaign'
    PRESS = 'PRESS', 'Press Release'

class Prospect(models.Model):
    email = models.EmailField(unique=True)
    entity_name = models.CharField(max_length=200, null=True, blank=True)
    first_name = models.CharField(max_length=200, null=True, blank=True)
    last_name = models.CharField(max_length=200, null=True, blank=True)
    address = models.CharField(max_length=200, null=True, blank=True)
    zip_code = models.CharField(max_length=20, null=True, blank=True)
    city = models.CharField(max_length=500, null=True, blank=True)
    phone = models.CharField(max_length=25, null=True, blank=True)
    users = models.ManyToManyField(get_user_model(), blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_prospects'
    )
    modified_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='modified_prospects'
    )
    modified_at = models.DateTimeField(auto_now=True)

    class Meta:
        permissions = [
            ("manage_prospects", "Can manage prospects"),
            ("view_prospects", "Can view prospects"),
        ]

    def full_name(self):
        return f'{self.first_name} {self.last_name}'

    def __str__(self):
        return ' - '.join(filter(None, [self.entity_name, self.first_name, self.last_name, f"({self.email})"]))

class Status(models.Model):
    name = models.CharField(max_length=100, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class ProspectStatus(models.Model):
    prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE)
    status = models.ForeignKey(Status, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

class Event(models.Model):
    date = models.DateTimeField(default=timezone.now)
    type = models.CharField(max_length=10, choices=EventType.choices)
    description = models.TextField()
    attachment_text = models.TextField(blank=True)
    prospects = models.ManyToManyField(Prospect, related_name='events')
    status = models.CharField(max_length=20, choices=[
        ('PLANNED', 'Planned'),
        ('ACTIVE', 'Active'),
        ('COMPLETED', 'Completed'),
    ])
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_events'
    )
    modified_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='modified_events'
    )
    modified_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        permissions = [
            ("manage_events", "Can manage events"),
            ("view_events", "Can view events"),
        ]

    def __str__(self):
        return f"{self.get_type_display()} - {self.date.date()}"

class EmailCampaign(models.Model):
    event = models.OneToOneField(Event, on_delete=models.CASCADE)
    subject = models.CharField(max_length=200)
    content = models.TextField()
    sent_at = models.DateTimeField(null=True, blank=True)

class EmailTracker(models.Model):
    campaign = models.ForeignKey(EmailCampaign, on_delete=models.CASCADE)
    prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE)
    tracking_id = models.UUIDField(default=uuid.uuid4, editable=False)
    sent = models.BooleanField(default=False)
    sent_at = models.DateTimeField(null=True, blank=True)
    opened = models.BooleanField(default=False)
    opened_at = models.DateTimeField(null=True, blank=True)
    clicked = models.BooleanField(default=False)
    clicked_at = models.DateTimeField(null=True, blank=True)
    error_message = models.TextField(blank=True)

    class Meta:
        unique_together = ['campaign', 'prospect']
