package playbooks

import (
	"context"
	"fmt"

	"apps/backend/internal/logic/growthmap"
	"apps/backend/internal/middleware"
	"apps/backend/internal/module/growth/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ListPlaybooksLogic) ListPlaybooks(req *types.ListPlaybooksReq) (*types.PlaybookListData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	list, total, err := l.svcCtx.Growth.ListPlaybooks(l.ctx, uid, req.Kind, req.Niche, req.Mine, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}
	out := make([]types.PlaybookPublic, 0, len(list))
	for _, p := range list {
		out = append(out, types.PlaybookPublic{
			Id: p.ID, Kind: p.Kind, Title: p.Title, Niche: p.Niche, Body: p.Body,
			Anonymous: p.Anonymous, AuthorLabel: usecase.PlaybookAuthorLabel(p, uid),
			ImportCount: p.ImportCount, CreatedAt: p.CreatedAt, Mine: p.OwnerUID == uid,
		})
	}
	return &types.PlaybookListData{List: out, Pagination: growthmap.Pagination(req.Page, req.PageSize, total)}, nil
}
