from django.db import models
from django.core.validators import MinLengthValidator
from django.contrib.auth import get_user_model

class Article(models.Model):
    title = models.CharField(
        max_length=200, null=False, 
        blank=False, verbose_name='Заголовок',
        validators=[MinLengthValidator(12)]
    )
    text = models.TextField(
        null=False, blank=False, verbose_name='Текст',
    )
    author = models.ForeignKey(
        get_user_model(), on_delete=models.CASCADE, 
        related_name='articles', verbose_name='Автор'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата обновления')
    
    tags_old = models.ManyToManyField('webapp.Tag', related_name='articles_set', through='webapp.ArticleTag')
    tags = models.ManyToManyField('webapp.Tag', related_name='articles')

    class Meta:
        verbose_name = 'статья'
        verbose_name_plural = 'статьи'
        permissions = [
            ('can_eat_pizza', 'Может съесть пиццу'),
        ]

    def __str__(self):
        return f'{self.id} {self.title}'


class Comment(models.Model):
    article = models.ForeignKey(
        'webapp.Article',
        related_name='comments',
        on_delete=models.CASCADE,
        verbose_name='Статья'
    )
    text = models.TextField(max_length=400, verbose_name='Текст')
    author = models.CharField(max_length=40, blank=True, default='Аноним', verbose_name='Автор')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата обновления')

    def __str__(self):
        return self.text[:20]


class Tag(models.Model):
    name = models.CharField(max_length=30, verbose_name='Тег')

    def __str__(self):
        return self.name


class ArticleTag(models.Model):
    article = models.ForeignKey('webapp.Article', on_delete=models.CASCADE, related_name='article_tags')
    tag = models.ForeignKey('webapp.Tag', on_delete=models.CASCADE, related_name='tag_articles')
    created_at = models.DateTimeField(auto_now_add=True)
