# backend/formulas/views/favorite.py
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from formulas.models.formula import Formula
from formulas.models.favorite import FavoriteFormula
from formulas.serializers.formula import FormulaSerializer

class FavoriteFormulaViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    @action(detail=False, methods=['get'])
    def list(self, request):
        favorites = FavoriteFormula.objects.filter(user=request.user)
        formulas = [fav.formula for fav in favorites]
        serializer = FormulaSerializer(formulas, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def add(self, request, pk=None):
        try:
            formula = Formula.objects.get(pk=pk)
        except Formula.DoesNotExist:
            return Response({"detail": "Formula not found."}, status=404)

        fav, created = FavoriteFormula.objects.get_or_create(user=request.user, formula=formula)
        if not created:
            return Response({"detail": "Already in favorites."}, status=400)

        return Response({"detail": "Added to favorites."}, status=200)

    @action(detail=True, methods=['delete'])
    def remove(self, request, pk=None):
        try:
            fav = FavoriteFormula.objects.get(user=request.user, formula_id=pk)
            fav.delete()
            return Response({"detail": "Removed from favorites."}, status=204)
        except FavoriteFormula.DoesNotExist:
            return Response({"detail": "Not in favorites."}, status=404)
