package demo

import (
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/utils"
	"git.apinb.com/ops/sample/internal/models"
	"github.com/gin-gonic/gin"
)

type CreateRequest struct {
	Name string `json:"name" binding:"required,max=255"`
	Age  int    `json:"age"`
}

type UpdateRequest struct {
	Name string `json:"name" binding:"required,max=255"`
	Age  int    `json:"age"`
}

type ListReply struct {
	Total int64              `json:"total"`
	List  []models.SampleDemo `json:"list"`
}

func Create(ctx *gin.Context) {
	var req CreateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		infra.Response.Error(ctx, errcode.ErrInvalidArgument)
		return
	}

	data := models.SampleDemo{
		Name: req.Name,
		Age:  req.Age,
	}
	data.Identity = utils.UUID()
	data.Status = 1
	if err := models.CreateSampleDemo(&data); err != nil {
		infra.Response.Error(ctx, err)
		return
	}
	infra.Response.Success(ctx, data)
}

func List(ctx *gin.Context) {
	page := utils.String2Int(ctx.DefaultQuery("page", "1"))
	size := utils.String2Int(ctx.DefaultQuery("size", "20"))
	if page < 1 {
		page = 1
	}
	if size < 1 || size > 100 {
		size = 20
	}

	list, total, err := models.ListSampleDemos(page, size)
	if err != nil {
		infra.Response.Error(ctx, err)
		return
	}
	infra.Response.Success(ctx, ListReply{Total: total, List: list})
}

func Get(ctx *gin.Context) {
	identity := ctx.Param("identity")
	if identity == "" {
		infra.Response.Error(ctx, errcode.ErrInvalidArgument)
		return
	}

	data, err := models.GetSampleDemoByField("identity", identity)
	if err != nil {
		infra.Response.Error(ctx, err)
		return
	}
	infra.Response.Success(ctx, data)
}

func Update(ctx *gin.Context) {
	identity := ctx.Param("identity")
	if identity == "" {
		infra.Response.Error(ctx, errcode.ErrInvalidArgument)
		return
	}

	var req UpdateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		infra.Response.Error(ctx, errcode.ErrInvalidArgument)
		return
	}

	data, err := models.GetSampleDemoByField("identity", identity)
	if err != nil {
		infra.Response.Error(ctx, err)
		return
	}

	data.Name = req.Name
	data.Age = req.Age
	if err := models.UpdateSampleDemo(data); err != nil {
		infra.Response.Error(ctx, err)
		return
	}
	infra.Response.Success(ctx, data)
}

func Delete(ctx *gin.Context) {
	identity := ctx.Param("identity")
	if identity == "" {
		infra.Response.Error(ctx, errcode.ErrInvalidArgument)
		return
	}

	data, err := models.GetSampleDemoByField("identity", identity)
	if err != nil {
		infra.Response.Error(ctx, err)
		return
	}

	if err := models.DeleteSampleDemo(data); err != nil {
		infra.Response.Error(ctx, err)
		return
	}
	infra.Response.Success(ctx, identity)
}
