package handler

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

	"github.com/zs/InsightReply/internal/service"
)

type UserHandler struct {
	svc *service.UserService
}

func NewUserHandler(svc *service.UserService) *UserHandler {
	return &UserHandler{svc: svc}
}

func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Email    string `json:"email"`
		Password string `json:"password"`
		Identity string `json:"identity"`
	}

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

	user, err := h.svc.Register(body.Email, body.Password, body.Identity)
	if err != nil {
		log.Printf("[Register] Failed to register user %s: %v", body.Email, err)
		SendError(w, http.StatusInternalServerError, 5001, "Failed to register user: "+err.Error())
		return
	}

	SendSuccess(w, user)
}

func (h *UserHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
	// Assumes JWTAuth middleware has placed userID in context
	userID := r.Context().Value("userID").(string)

	user, err := h.svc.GetUserByID(userID)
	if err != nil {
		SendError(w, http.StatusNotFound, 4004, "User not found")
		return
	}

	SendSuccess(w, user)
}

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

	var body struct {
		IdentityLabel      string `json:"identity_label"`
		LanguagePreference string `json:"language_preference"`
	}

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

	user, err := h.svc.UpdatePreferences(userID, body.IdentityLabel, body.LanguagePreference)
	if err != nil {
		SendError(w, http.StatusInternalServerError, 5001, "Failed to update preferences")
		return
	}

	SendSuccess(w, user)
}
