package WechatServer

import (
	"context"

	"wechat-api/ent/predicate"
	"wechat-api/ent/server"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetServerListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetServerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetServerListLogic {
	return &GetServerListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetServerListLogic) GetServerList(req *types.ServerListReq) (*types.ServerListResp, error) {
	var predicates []predicate.Server
	if req.Name != nil {
		predicates = append(predicates, server.NameContains(*req.Name))
	}
	if req.PublicIp != nil {
		predicates = append(predicates, server.PublicIPContains(*req.PublicIp))
	}
	if req.PrivateIp != nil {
		predicates = append(predicates, server.PrivateIPContains(*req.PrivateIp))
	}
	data, err := l.svcCtx.DB.Server.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.ServerListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.ServerInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:    &v.Status,
				Name:      &v.Name,
				PublicIp:  &v.PublicIP,
				PrivateIp: &v.PrivateIP,
				AdminPort: &v.AdminPort,
			})
	}

	return resp, nil
}
