from app.extensions import db
from datetime import datetime
from slugify import slugify
from sqlalchemy.event import listens_for

class Article(db.Model):
    """Modelo para los artículos del blog."""
    __tablename__ = 'articles'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    slug = db.Column(db.String(255), unique=True, nullable=False)
    summary = db.Column(db.String(500))
    content = db.Column(db.Text)
    featured_image = db.Column(db.String(255))
    is_published = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f'<Article {self.id}: {self.title}>'
    
    @property
    def formatted_created_date(self):
        """Retorna fecha formateada como YYYY-MM-DD."""
        return self.created_at.strftime('%Y-%m-%d')
    
    def to_dict(self):
        """Convierte el modelo a un diccionario para fácil serialización."""
        return {
            'id': self.id,
            'title': self.title,
            'slug': self.slug,
            'summary': self.summary,
            'content': self.content,
            'featured_image': self.featured_image,
            'is_published': self.is_published,
            'created_at': self.formatted_created_date
        }


@listens_for(Article, 'before_insert')
@listens_for(Article, 'before_update')
def generate_slug(mapper, connect, target):
    """Genera automáticamente un slug único si no se proporciona uno."""
    if not target.slug:
        target.slug = slugify(target.title)
        
        # Verificar si el slug ya existe y añadir un sufijo si es necesario
        base_slug = target.slug
        counter = 1
        while Article.query.filter(Article.slug == target.slug, Article.id != target.id).first():
            target.slug = f"{base_slug}-{counter}"
            counter += 1
