package handler

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

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

type AuthHandler struct {
	svc *service.AuthService
}

func NewAuthHandler(svc *service.AuthService) *AuthHandler {
	return &AuthHandler{svc: svc}
}

// Login handles user authentication and returns a JWT token
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}

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

	if body.Email == "" || body.Password == "" {
		SendError(w, http.StatusBadRequest, 4001, "Email and Password are required")
		return
	}

	token, err := h.svc.Login(body.Email, body.Password)
	if err != nil {
		SendError(w, http.StatusUnauthorized, 4001, err.Error())
		return
	}

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