package inspire

import (
	"context"

	"apps/backend/internal/middleware"
	inspireDomain "apps/backend/internal/module/inspire/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *SaveInspireElementLogic) SaveInspireElement(req *types.InspireElementSaveReq) (*types.InspireElementPublic, error) {
	if l.svcCtx.Inspire == nil {
		return nil, response.Biz(503, 503001, "inspire not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	el, err := l.svcCtx.Inspire.SaveElement(l.ctx, uid, &inspireDomain.Element{
		ID: req.Id, Kind: req.Kind, Title: req.Title, Body: req.Body, RefID: req.RefId, Reusable: req.Reusable,
	})
	if err != nil {
		return nil, err
	}
	out := types.ElementFromDomain(el)
	return &out, nil
}
