import datetime

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
from django.utils.text import Truncator
from phonenumber_field.modelfields import PhoneNumberField


class User(AbstractUser):
    pass


class Contact(models.Model):
    phone_number = PhoneNumberField()
    display_name = models.CharField(max_length=250)

    def __str__(self):
        return self.display_name


class Message(models.Model):
    sender = models.ForeignKey(
        Contact,
        on_delete=models.PROTECT,
        related_name="messages",
    )
    content = models.TextField(blank=True)
    received_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["-received_at"]

    def __str__(self):
        truncator = Truncator(self.content)
        truncated_content = truncator.words(15)
        return f"De {self.sender}: {truncated_content}"


class Media(models.Model):
    message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name="media_files",
    )
    file = models.FileField()

    def __str__(self):
        return f"Envoyé avec '{self.message}'"

    @property
    def sender(self):
        return self.message.sender
