import { createHttpError } from "../../../utils/http.js";
import {
  getCloudtentaclesSourceConfig,
  getCloudtentaclesSourceByKey,
} from "../../platforms/cloudtentacles/source-config-service.js";
import {
  getCloudtentaclesSessionState,
  getCloudtentaclesSessionStateByKey,
} from "../../platforms/cloudtentacles/session-state-service.js";
import { normalizeStringArray } from "./domain.js";

export function resolvePersistedCloudtentaclesContext(sourceKey = "default") {
  const source =
    getCloudtentaclesSourceByKey(sourceKey) || getCloudtentaclesSourceConfig();
  const session =
    getCloudtentaclesSessionStateByKey(sourceKey) ||
    getCloudtentaclesSessionState();
  const token = String(session.token || "").trim();

  if (!token) {
    throw createHttpError(
      "当前 cloudtentacles 没有可用 token，请先到平台配置完成登录校验",
      {
        statusCode: 409,
        errorCode: "kuaishou_cloud_missing_cloud_token",
      }
    );
  }

  return {
    baseUrl:
      String(session.baseUrl || source.baseUrl || "").trim() ||
      "https://123.207.217.176",
    token,
    deviceId: String(session.deviceId || source.deviceId || "-").trim() || "-",
    deviceType: Number(session.deviceType ?? source.deviceType ?? 0),
  };
}

/**
 * 按优先级依次尝试 cloudSourceKey 和 fallbacks 列表中的账号，
 * 找到第一个有可用 token 的账号返回其 context。
 * 将实际使用的 resolvedSourceKey 也返回，确保后续操作（退号、发货等）
 * 使用同一个 sourceKey，防止跨账号操作导致数据不一致。
 */
export function resolvePersistedCloudtentaclesContextWithFallback(
  primarySourceKey = "default",
  fallbacks = []
) {
  const candidates = [
    String(primarySourceKey || "default").trim() || "default",
    ...normalizeStringArray(fallbacks),
  ];

  const uniqueCandidates = [...new Set(candidates)];

  let lastError = null;

  for (const sourceKey of uniqueCandidates) {
    const source = getCloudtentaclesSourceByKey(sourceKey);
    const session = getCloudtentaclesSessionStateByKey(sourceKey);

    if (!source) continue;

    const token = String(session?.token || "").trim();
    if (!token) {
      lastError = createHttpError(
        `cloudtentacles 账号 ${sourceKey} 没有可用 token`,
        { statusCode: 409, errorCode: "kuaishou_cloud_missing_cloud_token" }
      );
      continue;
    }

    return {
      baseUrl:
        String(session.baseUrl || source.baseUrl || "").trim() ||
        "https://123.207.217.176",
      token,
      deviceId:
        String(session.deviceId || source.deviceId || "-").trim() || "-",
      deviceType: Number(session.deviceType ?? source.deviceType ?? 0),
      resolvedSourceKey: sourceKey,
    };
  }

  throw (
    lastError ||
    createHttpError(
      "所有 cloudtentacles 备选账号均不可用，请先到平台配置完成登录校验",
      { statusCode: 409, errorCode: "kuaishou_cloud_all_source_keys_exhausted" }
    )
  );
}
