package plays

import (
	"context"
	"errors"

	"apps/backend/internal/middleware"
	"apps/backend/internal/module/studio/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GeneratePlayStepLogic) GeneratePlayStep(req *types.PlayGenerateStepReq) (*types.PlayGenerateStepData, error) {
	if l.svcCtx.Studio == nil {
		return nil, response.Biz(503, 503001, "studio not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	text, err := l.svcCtx.Studio.GeneratePlayStep(
		l.ctx, uid,
		req.PersonaId, req.Context, req.Topic, req.SpeakerLabel, req.IsLead, req.Mode,
	)
	if err != nil {
		if errors.Is(err, domain.ErrValidation) || errors.Is(err, domain.ErrNoAccount) {
			return nil, response.Biz(400, 400001, err.Error())
		}
		return nil, err
	}
	return &types.PlayGenerateStepData{Text: text}, nil
}
