package usecase

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	domusecase "haixun-backend/internal/model/threads_account/domain/usecase"
)

func (u *threadsAccountUseCase) ResolveMemberThreadsPublishCredential(
	ctx context.Context,
	tenantID, ownerUID string,
) (*domusecase.ThreadsPublishCredential, error) {
	if err := requireActor(tenantID, ownerUID); err != nil {
		return nil, err
	}
	member, err := u.members.GetByUID(ctx, tenantID, ownerUID)
	if err != nil {
		return nil, err
	}
	activeID := strings.TrimSpace(member.ActiveThreadsAccountID)
	if activeID == "" {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("請先選定經營帳號")
	}
	account, err := u.assertOwned(ctx, tenantID, ownerUID, activeID)
	if err != nil {
		return nil, err
	}
	secrets, err := u.secretsRepo.FindByAccountID(ctx, account.ID)
	if err != nil {
		return nil, err
	}
	token := ""
	if secrets != nil {
		token = strings.TrimSpace(secrets.APIAccessToken)
	}
	userID := strings.TrimSpace(account.ThreadsUserID)
	apiConnected := token != "" && userID != ""
	if !apiConnected {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("請先完成 Threads API 連線後再發送留言")
	}
	prefs, _ := u.loadConnectionPrefs(ctx, account.ID)
	if prefs.DevMode && !prefs.PublishViaApi {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("開發模式請在連線設定啟用 API 發文，或改用手動貼上留言")
	}
	return &domusecase.ThreadsPublishCredential{
		AccountID:     account.ID,
		ThreadsUserID: userID,
		AccessToken:   token,
	}, nil
}
