package threads

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *RefreshThreadsAccountLogic) RefreshThreadsAccount(req *types.ThreadsAccountIdPath) (*types.ThreadsAccountPublic, error) {
	if l.svcCtx.Threads == nil {
		return nil, response.Biz(503, 503001, "threads module not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	a, err := l.svcCtx.Threads.Refresh(l.ctx, uid, req.Id)
	if err != nil {
		// still return account snapshot when refresh failed but updated
		if a != nil {
			pub := types.ThreadsAccountFromModel(a)
			return &pub, err
		}
		return nil, err
	}
	pub := types.ThreadsAccountFromModel(a)
	return &pub, nil
}
