package settings

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/module/ai"
	"apps/backend/internal/module/member/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

// GetAi — 一次回傳：已存設定（含 selected model）+ 指定 provider 的模型清單（5 分鐘快取）
func (l *GetAiLogic) GetAi(req *types.GetAiReq) (*types.AiSettingsData, error) {
	uid, _ := middleware.UIDFrom(l.ctx)
	st, err := l.svcCtx.Members.GetSettings(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	if st == nil {
		st = domain.DefaultSettings(uid)
	}
	// normalize stored provider
	st.Provider = ai.NormalizeProvider(st.Provider)

	modelsProvider := st.Provider
	if req != nil && req.Provider != "" {
		modelsProvider = ai.NormalizeProvider(req.Provider)
	}

	out := buildAiSettingsData(l.ctx, l.svcCtx, st, modelsProvider)
	// when models_provider == saved provider, keep Model in sync with SelectedModel
	if out.ModelsProvider == out.Provider {
		out.Model = out.SelectedModel
		out.ResearchModel = out.SelectedModel
	}
	return out, nil
}
