package utils

import (
	"gorm.io/gorm/utils"
)

type Result struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

// 空集合
var emptyList = make([]interface{}, 0)

type PageResult[T any] struct {
	List   []T    `json:"list"`
	Anchor string `json:"anchor,omitempty"`
	End    *bool  `json:"end,omitempty"`
}

func Ok(Data any) Result {
	return Result{
		Code: ok.ToInt(),
		Data: Data,
	}
}

func OkPageResult[T any](anchor any, end bool, list []T) Result {
	return Result{
		Code: ok.ToInt(),
		Data: PageResult[T]{
			List:   list,
			Anchor: utils.ToString(anchor),
			End:    &end,
		},
	}
}

func OkEmptyPageResult(anchor any) Result {
	return Result{
		Code: ok.ToInt(),
		Data: PageResult[interface{}]{
			Anchor: ToString(anchor),
			End:    ToPtr(true),
			List:   emptyList,
		},
	}
}

func Failed(msg string) Result {
	return Result{
		Code: failed.ToInt(),
		Msg:  msg,
	}
}

func Error(err error) Result {
	return Result{
		Code: failed.ToInt(),
		Msg:  err.Error(),
	}
}

type Code int

const ok Code = 0
const failed Code = -1

func (code Code) ToInt() int {
	return int(code)
}