from django.contrib.auth import get_user_model
from django.db import models
from datetime import datetime

class Author(models.Model):
    name = models.CharField(max_length=50, null=False, verbose_name="Автор")

    def __str__(self):
        return self.name


class Article(models.Model):
    title = models.CharField(max_length=250, null=False)
    body = models.CharField(max_length=2000, null=True)
    created_at = models.DateTimeField(auto_now_add=True, null=False)

    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.SET_DEFAULT,
        null=True, related_name='articles', default=1)
    tags = models.ManyToManyField(
        'articles.Tag',
        related_name='articles',
        blank=True
    )

    def __str__(self):
        return f"{self.id}. {self.title[:20]}"

    class Meta:
        permissions = [
            ('can_read_article', 'Может читать статьи')
        ]


class Comment(models.Model):
    article = models.ForeignKey(
        "articles.Article",
        related_name="comments",
        on_delete=models.CASCADE,
        verbose_name="Статья")
    text = models.TextField(max_length=400, verbose_name="Комментарий")
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.SET_DEFAULT,
        null=True, related_name='author_of_comment', default=1)
    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=31, verbose_name='Тег')
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Время создания'
    )

    def __str__(self):
        return self.name


class ArticleTag(models.Model):
    article = models.ForeignKey(
        'articles.Article',
        related_name='article_tags',
        on_delete=models.CASCADE,
        verbose_name="Статья")
    tag = models.ForeignKey(
        'articles.Tag',
        related_name='tag_articles',
        on_delete=models.CASCADE,
        verbose_name="Тег")

    def __str__(self):
        return f"{self.article} | {self.tag}"

