package handler

import (
	"kra/internal/service"
	"kra/internal/service/dto"

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

type APIToken struct {
	service *service.TokenService
}

func NewAPIToken(service *service.TokenService) *APIToken {
	return &APIToken{service: service}
}

func (h *APIToken) Create(c *gin.Context) {
	var req dto.CreateAPITokenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	token, err := h.service.CreateAPIToken(c.Request.Context(), req.UserID, req.AuthorityID, req.Days, req.Remark)
	if err != nil {
		Fail(c, "签发失败: "+err.Error())
		return
	}
	Write(c, CodeSuccess, gin.H{"token": token}, "签发成功")
}

func (h *APIToken) List(c *gin.Context) {
	var req dto.APITokenListRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	items, total, err := h.service.APITokens(c.Request.Context(), req.Page, req.PageSize, req.UserID, req.Status)
	if err != nil {
		Fail(c, "获取失败")
		return
	}
	Write(c, CodeSuccess, PageResult{List: items, Total: total, Page: req.Page, PageSize: req.PageSize}, "获取成功")
}

func (h *APIToken) Delete(c *gin.Context) {
	var req dto.IDRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.DisableAPIToken(c.Request.Context(), req.ID); err != nil {
		Fail(c, "作废失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "作废成功")
}
