package research

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ResearchSearchLogic) ResearchSearch(req *types.ResearchSearchReq) (*types.ResearchSearchData, error) {

	if l.svcCtx.Inspire == nil {
		return nil, response.Biz(503, 503001, "research not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	hits, err := l.svcCtx.Inspire.ResearchSearch(l.ctx, uid, req.Query)
	if err != nil {
		return nil, err
	}
	out := make([]types.ResearchHitPublic, 0, len(hits))
	for _, h := range hits {
		out = append(out, types.ResearchHitFromDomain(h))
	}
	return &types.ResearchSearchData{List: out}, nil

}
