from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone

class User(AbstractUser):
    avatar = models.CharField(max_length=255, null=True, blank=True, verbose_name='头像')
    bio = models.TextField(null=True, blank=True, verbose_name='个人简介')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'auth_user'

class BaseModel(models.Model):
    """基础抽象模型，提供通用字段"""
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        abstract = True

class SoftDeleteModel(BaseModel):
    """软删除模型"""
    is_deleted = models.BooleanField(default=False, verbose_name='是否删除')

    class Meta:
        abstract = True

    def delete(self, *args, **kwargs):
        self.is_deleted = True
        self.save()

class Category(BaseModel):
    """分类模型"""
    name = models.CharField(max_length=100, verbose_name='���称')
    description = models.TextField(blank=True, verbose_name='描述')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = '分类'

class Tag(BaseModel):
    """标签模型"""
    name = models.CharField(max_length=50, verbose_name='名称')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = '标签'

class Post(SoftDeleteModel):
    """帖子模型"""
    title = models.CharField(max_length=200, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    summary = models.TextField(blank=True, null=True, verbose_name='摘要')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='分类')
    tags = models.ManyToManyField(Tag, verbose_name='标签')
    views_count = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.title

    @property
    def likes_count(self):
        return self.like_set.count()

    @property
    def comments_count(self):
        return self.comment_set.filter(is_deleted=False).count()

    class Meta:
        verbose_name = '帖子'
        verbose_name_plural = '帖子'

class Comment(SoftDeleteModel):
    """评论模型"""
    content = models.TextField(verbose_name='内容')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='帖子')
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父评论')

    @property
    def likes_count(self):
        return self.like_set.count()

    @property
    def replies_count(self):
        return self.comment_set.filter(is_deleted=False).count()

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = '评论'

class Like(BaseModel):
    """点赞���型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    post = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE, verbose_name='帖子')
    comment = models.ForeignKey(Comment, null=True, blank=True, on_delete=models.CASCADE, verbose_name='评论')

    class Meta:
        verbose_name = '点赞'
        verbose_name_plural = '点赞'
        constraints = [
            models.CheckConstraint(
                check=(
                    models.Q(post__isnull=False, comment__isnull=True) |
                    models.Q(post__isnull=True, comment__isnull=False)
                ),
                name='like_post_xor_comment'
            ),
            models.UniqueConstraint(
                fields=['user', 'post'],
                condition=models.Q(post__isnull=False),
                name='unique_user_post_like'
            ),
            models.UniqueConstraint(
                fields=['user', 'comment'],
                condition=models.Q(comment__isnull=False),
                name='unique_user_comment_like'
            )
        ]
