package usecase

import (
	"context"
	"strings"

	"haixun-backend/internal/library/placement"
)

func (u *threadsAccountUseCase) ResolveMemberPlacementContext(
	ctx context.Context,
	tenantID, ownerUID string,
	research placement.ResearchSettings,
) (placement.MemberContext, error) {
	if err := requireActor(tenantID, ownerUID); err != nil {
		return placement.MemberContext{}, err
	}
	member, err := u.members.GetByUID(ctx, tenantID, ownerUID)
	if err != nil {
		return placement.MemberContext{}, err
	}
	activeID := member.ActiveThreadsAccountID
	prefs := defaultConnectionPrefs()
	apiConnected := false
	browserConnected := false
	apiToken := ""
	if activeID != "" {
		if account, err := u.assertOwned(ctx, tenantID, ownerUID, activeID); err == nil {
			loaded, err := u.loadConnectionPrefs(ctx, account.ID)
			if err == nil {
				prefs = loaded
			}
			browserConnected, apiConnected, _ = u.connectionFlags(ctx, account.ID)
			if apiConnected {
				if secrets, err := u.secretsRepo.FindByAccountID(ctx, account.ID); err == nil && secrets != nil {
					apiToken = strings.TrimSpace(secrets.APIAccessToken)
				}
			}
		}
	}
	ctxOut := placement.BuildMemberContext(
		tenantID,
		ownerUID,
		activeID,
		placement.ConnectionPrefsInput{
			DevMode:          prefs.DevMode,
			SearchSourceMode: prefs.SearchSourceMode,
		},
		apiConnected,
		browserConnected,
		research,
		prefs.ScrapeReplies,
		prefs.RepliesPerPost,
	)
	ctxOut.ThreadsAPIAccessToken = apiToken
	return ctxOut, nil
}
