package logic

import (
	"context"
	"errors"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

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

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

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

func (l *SyncWikiVectorLogic) SyncWikiVector(in *plant.SyncWikiVectorReq) (*plant.CommonResp, error) {
	if in.WikiId == "" {
		return nil, errors.New("wikiId 不能为空")
	}
	if l.svcCtx.Config.Ai.EmbeddingApiUrl == "" || l.svcCtx.Config.Ai.QdrantUrl == "" || l.svcCtx.Config.Ai.QdrantCollection == "" {
		return nil, errors.New("AI/RAG 未配置 EmbeddingApiUrl、QdrantUrl 或 QdrantCollection")
	}
	var wiki plantModel.Wiki
	if err := l.svcCtx.DB.Where("id = ?", in.WikiId).First(&wiki).Error; err != nil {
		return nil, err
	}
	if err := upsertWikiVector(l.ctx, l.svcCtx.Config, wiki); err != nil {
		return nil, err
	}
	if err := l.svcCtx.DB.Model(&plantModel.Wiki{}).Where("id = ?", in.WikiId).Update("is_vector_synced", true).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
