package auth

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

func (h *Handler) Register(router gin.IRouter) {
	router.POST("/auth/login", h.login)
}

func (h *Handler) login(c *gin.Context) {
	var input struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		abortWithError(c, http.StatusBadRequest, "invalid_request", "请求参数无效")
		return
	}
	token, err := h.service.Login(input.Email, input.Password)
	if err != nil {
		abortWithError(c, http.StatusUnauthorized, "invalid_credentials", "邮箱或密码错误")
		return
	}
	c.JSON(http.StatusOK, gin.H{"token": token})
}
