package system

import (
	"kra/internal/biz/system"
	"kra/pkg/response"
	"kra/pkg/utils"

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

type ApiApi struct{}

// CreateApiRequest 创建API请求
type CreateApiRequest struct {
	Path        string `json:"path" binding:"required"`
	Description string `json:"description" binding:"required"`
	ApiGroup    string `json:"apiGroup" binding:"required"`
	Method      string `json:"method" binding:"required"`
}

// UpdateApiRequest 更新API请求
type UpdateApiRequest struct {
	ID          uint   `json:"ID" binding:"required"`
	Path        string `json:"path" binding:"required"`
	Description string `json:"description" binding:"required"`
	ApiGroup    string `json:"apiGroup" binding:"required"`
	Method      string `json:"method" binding:"required"`
}

// DeleteApiRequest 删除API请求
type DeleteApiRequest struct {
	ID uint `json:"ID" binding:"required"`
}

// GetApiListRequest 获取API列表请求
type GetApiListRequest struct {
	Page        int    `json:"page"`
	PageSize    int    `json:"pageSize"`
	Path        string `json:"path"`
	Description string `json:"description"`
	ApiGroup    string `json:"apiGroup"`
	Method      string `json:"method"`
	OrderKey    string `json:"orderKey"`
	Desc        bool   `json:"desc"`
}

// GetApiByIdRequest 根据ID获取API请求
type GetApiByIdRequest struct {
	ID uint `json:"ID" binding:"required"`
}

// DeleteApisByIdsRequest 批量删除API请求
type DeleteApisByIdsRequest struct {
	Ids []uint `json:"ids" binding:"required"`
}

// CreateApi
// @Tags      SysApi
// @Summary   创建基础api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      CreateApiRequest               true  "api路径, api中文描述, api组, 方法"
// @Success   200   {object}  response.Response{msg=string}  "创建基础api"
// @Router    /api/createApi [post]
func (a *ApiApi) CreateApi(c *gin.Context) {
	var req CreateApiRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	api := &system.Api{
		Path:        req.Path,
		Description: req.Description,
		ApiGroup:    req.ApiGroup,
		Method:      req.Method,
	}

	if err := apiUsecase.CreateApi(c, api); err != nil {
		response.FailWithMessage("创建失败", c)
		return
	}

	response.OkWithMessage("创建成功", c)
}

// DeleteApi
// @Tags      SysApi
// @Summary   删除api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DeleteApiRequest               true  "ID"
// @Success   200   {object}  response.Response{msg=string}  "删除api"
// @Router    /api/deleteApi [post]
func (a *ApiApi) DeleteApi(c *gin.Context) {
	var req DeleteApiRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := apiUsecase.DeleteApi(c, req.ID); err != nil {
		response.FailWithMessage("删除失败", c)
		return
	}

	response.OkWithMessage("删除成功", c)
}

// UpdateApi
// @Tags      SysApi
// @Summary   修改基础api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      UpdateApiRequest               true  "api路径, api中文描述, api组, 方法"
// @Success   200   {object}  response.Response{msg=string}  "修改基础api"
// @Router    /api/updateApi [post]
func (a *ApiApi) UpdateApi(c *gin.Context) {
	var req UpdateApiRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	api := &system.Api{
		ID:          req.ID,
		Path:        req.Path,
		Description: req.Description,
		ApiGroup:    req.ApiGroup,
		Method:      req.Method,
	}

	if err := apiUsecase.UpdateApi(c, api); err != nil {
		response.FailWithMessage("修改失败", c)
		return
	}

	response.OkWithMessage("修改成功", c)
}

// GetApiList
// @Tags      SysApi
// @Summary   分页获取API列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      GetApiListRequest                                   true  "分页获取API列表"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取API列表,返回包括列表,总数,页码,每页数量"
// @Router    /api/getApiList [post]
func (a *ApiApi) GetApiList(c *gin.Context) {
	var req GetApiListRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	filters := make(map[string]interface{})
	if req.Path != "" {
		filters["path"] = req.Path
	}
	if req.Description != "" {
		filters["description"] = req.Description
	}
	if req.ApiGroup != "" {
		filters["api_group"] = req.ApiGroup
	}
	if req.Method != "" {
		filters["method"] = req.Method
	}

	list, total, err := apiUsecase.GetApiList(c, req.Page, req.PageSize, filters)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, "获取成功", c)
}

// GetApiById
// @Tags      SysApi
// @Summary   根据id获取api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      GetApiByIdRequest                                   true  "根据id获取api"
// @Success   200   {object}  response.Response{data=system.Api}  "根据id获取api,返回包括api详情"
// @Router    /api/getApiById [post]
func (a *ApiApi) GetApiById(c *gin.Context) {
	var req GetApiByIdRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	api, err := apiUsecase.GetApiById(c, req.ID)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(gin.H{"api": api}, "获取成功", c)
}

// GetAllApis
// @Tags      SysApi
// @Summary   获取所有的Api 不分页
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=[]system.Api,msg=string}  "获取所有的Api 不分页,返回包括api列表"
// @Router    /api/getAllApis [post]
func (a *ApiApi) GetAllApis(c *gin.Context) {
	authorityID := utils.GetUserAuthorityId(c)
	apis, err := apiUsecase.GetAllApis(c, authorityID)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(gin.H{"apis": apis}, "获取成功", c)
}

// DeleteApisByIds
// @Tags      SysApi
// @Summary   删除选中Api
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DeleteApisByIdsRequest         true  "ID"
// @Success   200   {object}  response.Response{msg=string}  "删除选中Api"
// @Router    /api/deleteApisByIds [delete]
func (a *ApiApi) DeleteApisByIds(c *gin.Context) {
	var req DeleteApisByIdsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := apiUsecase.DeleteApisByIds(c, req.Ids); err != nil {
		response.FailWithMessage("删除失败", c)
		return
	}

	response.OkWithMessage("删除成功", c)
}

// FreshCasbin
// @Tags      SysApi
// @Summary   刷新casbin缓存
// @accept    application/json
// @Produce   application/json
// @Success   200   {object}  response.Response{msg=string}  "刷新成功"
// @Router    /api/freshCasbin [get]
func (a *ApiApi) FreshCasbin(c *gin.Context) {
	if err := casbinUsecase.FreshCasbin(); err != nil {
		response.FailWithMessage("刷新失败", c)
		return
	}

	response.OkWithMessage("刷新成功", c)
}

// IgnoreApiRequest 忽略API请求
type IgnoreApiRequest struct {
	Path   string `json:"path" binding:"required"`
	Method string `json:"method" binding:"required"`
	Flag   bool   `json:"flag"` // true: 忽略, false: 取消忽略
}

// SyncApisRequest 同步API请求
type SyncApisRequest struct {
	NewApis    []*system.Api `json:"newApis"`
	DeleteApis []*system.Api `json:"deleteApis"`
}

// SyncApi
// @Tags      SysApi
// @Summary   同步API
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200   {object}  response.Response{msg=string}  "同步API"
// @Router    /api/syncApi [get]
func (a *ApiApi) SyncApi(c *gin.Context) {
	newApis, deleteApis, ignoreApis, err := apiUsecase.SyncApi(c)
	if err != nil {
		response.FailWithMessage("同步失败", c)
		return
	}

	response.OkWithData(gin.H{
		"newApis":    newApis,
		"deleteApis": deleteApis,
		"ignoreApis": ignoreApis,
	}, c)
}

// GetApiGroups
// @Tags      SysApi
// @Summary   获取API分组
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200   {object}  response.Response{msg=string}  "获取API分组"
// @Router    /api/getApiGroups [get]
func (a *ApiApi) GetApiGroups(c *gin.Context) {
	groups, apiGroupMap, err := apiUsecase.GetApiGroups(c)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithData(gin.H{
		"groups":      groups,
		"apiGroupMap": apiGroupMap,
	}, c)
}

// IgnoreApi
// @Tags      SysApi
// @Summary   忽略API
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      IgnoreApiRequest               true  "忽略API请求"
// @Success   200   {object}  response.Response{msg=string}  "忽略API"
// @Router    /api/ignoreApi [post]
func (a *ApiApi) IgnoreApi(c *gin.Context) {
	var req IgnoreApiRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := apiUsecase.IgnoreApi(c, req.Path, req.Method, req.Flag); err != nil {
		response.FailWithMessage("忽略失败", c)
		return
	}

	response.Ok(c)
}

// EnterSyncApi
// @Tags      SysApi
// @Summary   确认同步API
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      SyncApisRequest                true  "同步API请求"
// @Success   200   {object}  response.Response{msg=string}  "确认同步API"
// @Router    /api/enterSyncApi [post]
func (a *ApiApi) EnterSyncApi(c *gin.Context) {
	var req SyncApisRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := apiUsecase.EnterSyncApi(c, req.NewApis, req.DeleteApis); err != nil {
		response.FailWithMessage("同步失败", c)
		return
	}

	response.Ok(c)
}
