package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"git.rpuzonas.com/rpuzonas/go-rss-aggregator/internal/database"
	"github.com/go-chi/chi"
)


func (apiCfg *apiConfig) handlerFollowFeed(w http.ResponseWriter, r *http.Request, user User) {
	type parameters struct {
		FeedID int64 `json:"feed_id"`
	}

	decoder := json.NewDecoder(r.Body)
	params := parameters{}
	err := decoder.Decode(&params)
	if err != nil {
		respondWithError(w, 400, fmt.Sprintf("Error parsing JSON: %v", err))
		return
	}

	now := time.Now().UTC()
	feedFollow, err := apiCfg.DB.CreateFeedFollow(r.Context(), database.CreateFeedFollowParams{
		UpdatedAt: now,
		CreatedAt: now,
		UserID: user.ID,
		FeedID: params.FeedID,
	})
	if err != nil {
		respondWithError(w, 400, fmt.Sprintf("Couldn't follow feed: %v", err))
		return
	}

	respondWithJSON(w, 200, databaseFeedFollowToFeedFollow(feedFollow))
}

func (apiCfg *apiConfig) handlerGetFeedFollows(w http.ResponseWriter, r *http.Request, user User) {
	feedFollows, err := apiCfg.DB.GetFeedFollowsByUser(r.Context(), user.ID)
	if err != nil {
		respondWithError(w, 400, fmt.Sprintf("Couldn't list feed follows: %v", err))
		return
	}

	respondWithJSON(w, 200, databaseFolllowFeedsToFollowFeeds(feedFollows))
}

func (apiCfg *apiConfig) handlerDeleteFeedFollow(w http.ResponseWriter, r *http.Request, user User) {
	feedFollowIDStr := chi.URLParam(r, "feedFollowID");
	feedFollowID, err := strconv.ParseInt(feedFollowIDStr, 10, 64)
	if err != nil {
		respondWithError(w, 400, fmt.Sprintf("Failed to parse feed id: %v", err))
		return
	}

	err = apiCfg.DB.DeleteFeedFollow(r.Context(), database.DeleteFeedFollowParams{
		UserID: user.ID,
		ID: feedFollowID,
	})
	if err != nil {
		respondWithError(w, 400, fmt.Sprintf("Failed to delete feed follow: %v", err))
		return
	}

	respondWithJSON(w, 200, struct{}{})
}
