from flask import render_template, request, Blueprint, abort
from app.models.article import Article
from sqlalchemy import desc
from . import blog_bp

@blog_bp.route('/')
def list_articles():
    try:
        page = request.args.get('page', 1, type=int)
        # Solo mostrar artículos publicados, ordenados por fecha de publicación
        pagination = Article.query.filter_by(published=True).order_by(desc(Article.published_at)).paginate(
            page=page, per_page=9, error_out=False
        )
        articles = pagination.items
        
        if not articles and page > 1:
            abort(404)  # Si no hay artículos y no estamos en la primera página
        
        return render_template('blog/list_articles.html', articles=articles, pagination=pagination)
    except Exception as e:
        # Log the error
        abort(500)

@blog_bp.route('/<slug>')
def article_detail(slug):
    try:
        article = Article.query.filter_by(slug=slug, published=True).first_or_404()
        return render_template('blog/article_detail.html', article=article)
    except Exception as e:
        # Log the error
        abort(404)
