package threads_account

import (
	"context"
	"math"

	cfdom "haixun-backend/internal/model/content_formula/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type ListContentFormulasLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListContentFormulasLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListContentFormulasLogic {
	return &ListContentFormulasLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *ListContentFormulasLogic) ListContentFormulas(req *types.ListContentFormulasHandlerReq) (*types.ListContentFormulasData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	page := int(req.Page)
	if page <= 0 {
		page = 1
	}
	pageSize := int(req.PageSize)
	if pageSize <= 0 {
		pageSize = 20
	}
	result, err := l.svcCtx.ContentFormula.List(l.ctx, cfdom.ListRequest{
		TenantID:   tenantID,
		OwnerUID:   uid,
		AccountID:  req.ID,
		SourceType: req.SourceType,
		Tag:        req.Tag,
		Page:       page,
		PageSize:   pageSize,
	})
	if err != nil {
		return nil, err
	}
	list := make([]types.ContentFormulaData, 0, len(result.Items))
	for _, item := range result.Items {
		list = append(list, toContentFormulaData(item))
	}
	totalPages := int64(0)
	if pageSize > 0 {
		totalPages = int64(math.Ceil(float64(result.Total) / float64(pageSize)))
	}
	return &types.ListContentFormulasData{
		Pagination: types.PaginationData{
			Total:      result.Total,
			Page:       int64(page),
			PageSize:   int64(pageSize),
			TotalPages: totalPages,
		},
		List: list,
	}, nil
}
