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 CompetitorMonitorHandler struct {
	svc *service.CompetitorMonitorService
}

func NewCompetitorMonitorHandler(svc *service.CompetitorMonitorService) *CompetitorMonitorHandler {
	return &CompetitorMonitorHandler{svc: svc}
}

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

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

	SendSuccess(w, monitors)
}

func (h *CompetitorMonitorHandler) CreateMonitor(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 monitor model.CompetitorMonitor
	if err := json.NewDecoder(r.Body).Decode(&monitor); err != nil {
		SendError(w, http.StatusBadRequest, 4001, "Invalid request body")
		return
	}

	monitor.UserID = userID

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

	SendSuccess(w, monitor)
}

func (h *CompetitorMonitorHandler) DeleteMonitor(w http.ResponseWriter, r *http.Request) {
	userID := r.Context().Value("userID").(string)
	monitorID := chi.URLParam(r, "id")

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

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