package user

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"go.uber.org/zap"

	error2 "github.com/pingcap-inc/clinic/pkg/api/error"
	"github.com/pingcap-inc/clinic/pkg/auth/session"
	"github.com/pingcap-inc/clinic/pkg/config"
	"github.com/pingcap-inc/clinic/pkg/db/model"
)

type UserService struct {
	cfg    *config.Config
	secret []byte
}

func NewUserService(cfg *config.Config) *UserService {
	return &UserService{
		cfg:    cfg,
		secret: []byte(cfg.DBaasConfig.DashboardConfig.SessionSecret),
	}
}

// @Summary		Get profile
// @Tags			User
// @Description	get profile
// @Produce		json
// @Param			x-csrf-token	header		string	true	"get value from login.ValidationResp response"
// @Success		200				{object}	UserResp
// @Router			/user/profile [get]
func Profile(c *gin.Context) {
	u := session.GetUser(c)
	if u == nil {
		_ = c.Error(error2.ErrNotFound.New("the user is not found"))
		return
	}
	user, err := model.GetUserByUserName(u.Username)
	if err != nil {
		log.Error("get user failed", zap.Error(err))
		_ = c.Error(error2.ErrInternal.New("get user failed"))
		return
	}

	c.JSON(http.StatusOK, UserResp{
		Email:     u.Email,
		UserName:  u.Username,
		Internal:  u.Internal,
		CreatedAt: uint(user.CreatedAt.Unix()),
	})
}
