package settings

import (
	"context"
	"strings"

	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetThreadsLogic) GetThreads() (*types.ThreadsSettingsData, error) {
	id := strings.TrimSpace(l.svcCtx.Config.Platform.ThreadsAppId)
	secret := strings.TrimSpace(l.svcCtx.Config.Platform.ThreadsAppSecret)
	configured := id != "" && secret != ""

	web := strings.TrimRight(l.svcCtx.Config.PublicWebBase, "/")
	base := strings.TrimRight(l.svcCtx.Config.PublicAPIBase, "/")
	if base == "" && strings.HasPrefix(web, "https://") {
		base = web
	}
	if base == "" {
		base = "http://127.0.0.1:8888"
	}
	// Prefer actual runtime base from threads service if wired
	if l.svcCtx.Threads != nil && l.svcCtx.Threads.APIPublicBase != "" {
		base = strings.TrimRight(l.svcCtx.Threads.APIPublicBase, "/")
	}
	cb := base + "/api/v1/threads-accounts/oauth/callback"

	provider := "fake"
	hint := "未設定 Threads App Id/Secret（gateway Platform 或 THREADS_APP_*）。目前為 fake OAuth。"
	if configured {
		provider = "meta"
		hint = "請把下方 Callback URL 貼到 Meta App → Valid OAuth Redirect URIs。連帳請用 https 公開站（Crew）。"
		if strings.HasPrefix(cb, "http://") {
			hint += " ⚠ Callback 仍是 HTTP，Meta 會擋（error 1349187）。"
		}
	}

	return &types.ThreadsSettingsData{
		Provider:      provider,
		Configured:    configured,
		OauthReady:    true,
		ConnectPath:   "/app/crew",
		CallbackUrl:   cb,
		PublicWebBase: web,
		AppIdMasked:   maskAppID(id),
		Hint:          hint,
	}, nil
}

func maskAppID(id string) string {
	if id == "" {
		return ""
	}
	if len(id) <= 8 {
		return id[:1] + "…" + id[len(id)-1:]
	}
	return id[:4] + "…" + id[len(id)-4:]
}
