package handler

import (
	"encoding/json"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/google/uuid"
	"github.com/zs/InsightReply/internal/model"
	"github.com/zs/InsightReply/internal/service"
)

type CustomStrategyHandler struct {
	svc *service.CustomStrategyService
}

func NewCustomStrategyHandler(svc *service.CustomStrategyService) *CustomStrategyHandler {
	return &CustomStrategyHandler{svc: svc}
}

func (h *CustomStrategyHandler) ListStrategies(w http.ResponseWriter, r *http.Request) {
	userID := r.Context().Value("userID").(string)

	strategies, err := h.svc.ListStrategies(userID)
	if err != nil {
		SendError(w, http.StatusInternalServerError, 5001, "Failed to list strategies")
		return
	}

	SendSuccess(w, strategies)
}

func (h *CustomStrategyHandler) CreateStrategy(w http.ResponseWriter, r *http.Request) {
	userIDStr := r.Context().Value("userID").(string)
	userID, err := uuid.Parse(userIDStr)
	if err != nil {
		SendError(w, http.StatusUnauthorized, 4010, "Invalid user ID")
		return
	}

	var strategy model.UserCustomStrategy
	if err := json.NewDecoder(r.Body).Decode(&strategy); err != nil {
		SendError(w, http.StatusBadRequest, 4001, "Invalid request body")
		return
	}

	strategy.UserID = userID

	if err := h.svc.CreateStrategy(&strategy); err != nil {
		SendError(w, http.StatusInternalServerError, 5001, "Failed to create strategy")
		return
	}

	SendSuccess(w, strategy)
}

func (h *CustomStrategyHandler) DeleteStrategy(w http.ResponseWriter, r *http.Request) {
	userID := r.Context().Value("userID").(string)
	strategyID := chi.URLParam(r, "id")

	if err := h.svc.DeleteStrategy(strategyID, userID); err != nil {
		SendError(w, http.StatusInternalServerError, 5001, "Failed to delete strategy")
		return
	}

	SendSuccess(w, map[string]string{"status": "deleted"})
}
