# articles/views.py  (CAMBIO: convertir value a int y validar)
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Article, Reaction
from .forms import CommentForm


def article_list(request):
    articles = Article.objects.filter(status="published")
    return render(request, "articles/article_list.html", {"articles": articles})


def article_detail(request, slug):
    article = get_object_or_404(Article, slug=slug, status="published")
    comments = article.comments.filter(is_active=True)
    form = CommentForm()

    user_reaction = None
    if request.user.is_authenticated:
        user_reaction = Reaction.objects.filter(article=article, user=request.user).first()

    context = {
        "article": article,
        "comments": comments,
        "form": form,
        "user_reaction": user_reaction,
    }
    return render(request, "articles/article_detail.html", context)


@login_required
def add_comment(request, slug):
    article = get_object_or_404(Article, slug=slug, status="published")

    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.user = request.user
            comment.article = article
            comment.save()

    return redirect("article_detail", slug=slug)


@login_required
def react_article(request, slug, value):
    article = get_object_or_404(Article, slug=slug, status="published")

    try:
        value_int = int(value)
    except ValueError:
        return redirect("article_detail", slug=slug)

    if value_int not in (1, -1):
        return redirect("article_detail", slug=slug)

    reaction, created = Reaction.objects.get_or_create(
        article=article,
        user=request.user,
        defaults={"value": value_int},
    )

    if not created:
        reaction.value = value_int
        reaction.save()

    return redirect("article_detail", slug=slug)