from model_utils.models import TimeStampedModel

from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import gettext_lazy as _

from .utils import normalize_tag_name

User = get_user_model()


class Tag(TimeStampedModel):
    name = models.CharField(_("название"), max_length=255)
    normalized_name = models.CharField(
        _("нормализованное название"),
        max_length=255,
        unique=True,
        editable=False,
        blank=True,
    )

    class Meta:
        ordering = ("normalized_name",)
        verbose_name = _("Тег")
        verbose_name_plural = _("Теги")

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.normalized_name = normalize_tag_name(self.name)
        super().save(*args, **kwargs)


class UserTag(models.Model):
    tag = models.ForeignKey(
        Tag,
        verbose_name=_("тег"),
        related_name='user_tags',
        on_delete=models.PROTECT,
    )
    user = models.ForeignKey(
        User,
        verbose_name=_("пользователь"),
        related_name='tags',
        on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = _("Пользовательский тег")
        verbose_name_plural = _("Пользовательские теги")
