// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package threads_account

import (
	"context"

	"haixun-backend/internal/library/clock"
	libthreads "haixun-backend/internal/library/threadsapi"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *GetThreadsDiagnosticsLogic) GetThreadsDiagnostics(req *types.ThreadsAccountPath) (resp *types.ThreadsDiagnosticsData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	account, err := l.svcCtx.ThreadsAccount.Get(l.ctx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}
	smoke, smokeErr := l.svcCtx.ThreadsAccount.RunAPISmokeTest(l.ctx, tenantID, uid, req.ID)
	items := make([]types.ThreadsAPISmokeTestItem, 0, len(smoke))
	for _, item := range smoke {
		items = append(items, types.ThreadsAPISmokeTestItem{
			Scope: item.Scope, Name: item.Name, Status: item.Status, Message: item.Message, Count: item.Count,
		})
	}
	message := "診斷完成"
	if smokeErr != nil {
		message = smokeErr.Error()
	}
	return &types.ThreadsDiagnosticsData{
		AccountID: req.ID, CheckedAt: clock.NowUnixNano(), ApiConnected: account.ApiConnected,
		TokenExpiresAt: account.APITokenExpiresAt, Scopes: libthreads.DefaultOAuthScopes, Items: items, Message: message,
	}, nil
}
