syntax = "v1"

type (
	ThreadsAccountPublic {
		Id                 string `json:"id"`
		Username           string `json:"username"`
		DisplayName        string `json:"display_name"`
		Connection         string `json:"connection"` // connected|error|disconnected
		IsUsable           bool   `json:"is_usable"`
		AvatarColor        string `json:"avatar_color,optional"`
		AvatarUrl          string `json:"avatar_url,optional"`
		ErrorMessage       string `json:"error_message,optional"`
		SessionExpiresAt   int64  `json:"session_expires_at,optional"`
		SessionRefreshedAt int64  `json:"session_refreshed_at,optional"`
		// never expose access_token / refresh_token
	}

	ThreadsAccountListData {
		List []ThreadsAccountPublic `json:"list"`
	}

	ThreadsOAuthStartData {
		AuthorizeUrl string `json:"authorize_url"`
		State        string `json:"state"`
	}

	// Callback is query-string from Meta / fake provider (public).
	ThreadsOAuthCallbackReq {
		Code             string `form:"code,optional"`
		State            string `form:"state,optional"`
		Error            string `form:"error,optional"`
		ErrorReason      string `form:"error_reason,optional"`
		ErrorDescription string `form:"error_description,optional"`
	}

	ThreadsOAuthCallbackData {
		Ok      bool   `json:"ok"`
		Message string `json:"message,optional"`
		// RedirectURL for custom handler (browser flow)
		RedirectUrl string `json:"redirect_url,optional"`
	}

	ThreadsAccountIdPath {
		Id string `path:"id"`
	}

	// 擴充（含舊版）匯入 Chrome storageState；寫入 scout crawler-session 供 dev 模式海巡
	ImportThreadsAccountSessionReq {
		// path id + body
		Id           string `path:"id"`
		StorageState string `json:"storageState"`
	}

	ImportThreadsAccountSessionData {
		Success   bool   `json:"success"`
		Valid     bool   `json:"valid"`
		Synced    bool   `json:"synced"`
		AccountId string `json:"account_id"`
		Username  string `json:"username,optional"`
		Message   string `json:"message"`
		UpdateAt  int64  `json:"update_at,optional"`
	}
)

// Public OAuth callback (no JWT)
@server (
	group:  threads
	prefix: /api/v1/threads-accounts
)
service gateway {
	@handler ThreadsOAuthCallback
	get /oauth/callback (ThreadsOAuthCallbackReq) returns (ThreadsOAuthCallbackData)
}

@server (
	jwt:        Auth
	group:      threads
	prefix:     /api/v1/threads-accounts
	middleware: AuthJWT
)
service gateway {
	@handler ThreadsOAuthStart
	get /oauth/start returns (ThreadsOAuthStartData)

	@handler ListThreadsAccounts
	get / returns (ThreadsAccountListData)

	@handler RefreshThreadsAccount
	post /:id/refresh (ThreadsAccountIdPath) returns (ThreadsAccountPublic)

	// Chrome 擴充：匯入 Playwright storageState（舊路徑相容；實際存 crawler session）
	@handler ImportThreadsAccountSession
	post /:id/session/import (ImportThreadsAccountSessionReq) returns (ImportThreadsAccountSessionData)

	@handler DisconnectThreadsAccount
	delete /:id (ThreadsAccountIdPath) returns (OkData)
}
