package proxy

import (
	"context"

	"apps/backend/internal/middleware"
	usageDomain "apps/backend/internal/module/usage/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ExaSearchLogic) ExaSearch(req *types.SearchReq) (_ *types.SearchData, err error) {
	if l.svcCtx.Usage == nil || l.svcCtx.Search == nil || l.svcCtx.KeyResolver == nil {
		return nil, response.Biz(503, 503001, "search proxy not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	mode, apiKey, err := l.svcCtx.KeyResolver.ResolveKey(l.ctx, uid, usageDomain.MeterWebSearch)
	if err != nil {
		return nil, err
	}
	charge, err := reserveQuota(l.ctx, l.svcCtx, uid, usageDomain.MeterWebSearch, mode, "search", "proxy.search")
	if err != nil {
		return nil, err
	}
	defer charge.Settle(l.ctx, &err)
	hits, err := l.svcCtx.Search.Search(l.ctx, apiKey, req.Query, req.Limit)
	if err != nil {
		return nil, response.Biz(502, 502002, err.Error())
	}
	out := make([]types.SearchHit, 0, len(hits))
	for _, h := range hits {
		out = append(out, types.SearchHit{Title: h.Title, Url: h.URL, Snippet: h.Snippet})
	}
	return &types.SearchData{List: out, KeyMode: mode}, nil
}
