package playbooks

import (
	"context"
	"fmt"

	"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 PublishPlaybookLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *PublishPlaybookLogic) PublishPlaybook(req *types.PublishPlaybookReq) (*types.PlaybookPublic, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	p, err := l.svcCtx.Growth.PublishPlaybook(l.ctx, uid, req.Kind, req.Title, req.Niche, req.Body, req.Anonymous)
	if err != nil {
		return nil, err
	}
	return &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: true,
	}, nil
}
