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

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

// GeneratePlayScript — 一次產完整劇本（背景 job，可離開頁面）
func (l *GeneratePlayScriptLogic) GeneratePlayScript(req *types.PlayIdPath) (*types.PlayGenerateScriptData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	if l.svcCtx.Studio == nil {
		return nil, response.Biz(503, 503001, "studio not configured")
	}
	// 先確認 play 存在
	if _, err := l.svcCtx.Studio.GetPlay(l.ctx, uid, req.Id); err != nil {
		if errors.Is(err, domain.ErrNotFound) {
			return nil, response.Biz(404, 404001, "play not found")
		}
		if errors.Is(err, domain.ErrForbidden) {
			return nil, response.Biz(403, 403001, err.Error())
		}
		return nil, err
	}

	if l.svcCtx.Jobs != nil {
		j, err := l.svcCtx.Jobs.SchedulePlayGenerateScript(l.ctx, uid, req.Id, true)
		if err != nil {
			return nil, err
		}
		return &types.PlayGenerateScriptData{JobId: j.ID, Async: true}, nil
	}

	// 無 worker：同步一次產完（測試）
	n, err := l.svcCtx.Studio.GeneratePlayScript(l.ctx, uid, req.Id, true)
	if err != nil {
		if errors.Is(err, domain.ErrValidation) {
			return nil, response.Biz(400, 400001, err.Error())
		}
		return nil, err
	}
	_ = n
	return &types.PlayGenerateScriptData{JobId: "", Async: false}, nil
}
