package job

import (
	"context"
	"strings"

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

func makeCrawlerSearchFn(deps ScanPlacementDeps, tenantID, ownerUID string) placement.CrawlerSearchFn {
	return func(ctx context.Context, member placement.MemberContext, keyword string, limit int) ([]placement.DiscoverPost, error) {
		accountID := strings.TrimSpace(member.ActiveAccountID)
		if accountID == "" {
			return nil, placementErr("請先選定經營帳號並同步 Chrome Session")
		}
		session, err := deps.ThreadsAccount.GetBrowserSession(ctx, tenantID, ownerUID, accountID)
		if err != nil {
			return nil, err
		}
		return placement.RunExecCrawlerSearch(ctx, session.StorageState, keyword, limit)
	}
}

func placementErr(msg string) error {
	return &placementError{msg: msg}
}

type placementError struct {
	msg string
}

func (e *placementError) Error() string {
	return e.msg
}
