package admin

import (
	"context"

	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *ListMembersLogic) ListMembers(req *types.AdminListMembersReq) (resp *types.AdminListData, err error) {
	page, pageSize := req.Page, req.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	list, total, err := l.svcCtx.Members.ListPage(l.ctx, page, pageSize, req.Query, req.Status)
	if err != nil {
		return nil, err
	}
	items := make([]types.MemberPublic, 0, len(list))
	for _, m := range list {
		items = append(items, *types.MemberFromModel(m))
	}
	totalPages := int(total) / pageSize
	if int(total)%pageSize != 0 {
		totalPages++
	}
	if totalPages == 0 {
		totalPages = 1
	}
	return &types.AdminListData{
		List: items,
		Pagination: types.Pagination{Page: page, PageSize: pageSize, Total: total, TotalPages: totalPages},
	}, nil
}
