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 ListModelsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

// ListModels — 真拉 provider 模型 + 5 分鐘快取；並回 selected_model（若為目前存檔 provider）
func (l *ListModelsLogic) ListModels(req *types.ListModelsReq) (*types.ListModelsData, error) {
	provider := ai.NormalizeProvider(req.Provider)
	if provider == "" {
		provider = ai.ProviderXAI
	}
	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)
	}
	st.Provider = ai.NormalizeProvider(st.Provider)

	list, fromCache, modelsErr := loadModelsForProvider(l.ctx, l.svcCtx, st, provider)
	selected := ""
	if provider == st.Provider {
		selected = pickModel(st.Model, list)
	}
	return &types.ListModelsData{
		List:          list,
		Provider:      provider,
		SelectedModel: selected,
		FromCache:     fromCache,
		ModelsError:   modelsErr,
	}, nil
}
