package tutorial

import (
	"context"

	"wechat-api/ent/predicate"
	"wechat-api/ent/tutorial"
	"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 GetTutorialListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetTutorialListLogic) GetTutorialList(req *types.TutorialListReq) (*types.TutorialListResp, error) {
	var predicates []predicate.Tutorial
	if req.Title != nil {
		predicates = append(predicates, tutorial.TitleContains(*req.Title))
	}
	if req.Content != nil {
		predicates = append(predicates, tutorial.ContentContains(*req.Content))
	}
	data, err := l.svcCtx.DB.Tutorial.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.TutorialInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				EmployeeId: &v.EmployeeID,
				Index:      &v.Index,
				Title:      &v.Title,
				Content:    &v.Content,
			})
	}

	return resp, nil
}
