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

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

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

  let lastError = null;

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

    if (!source) continue;
    if (source.enabled === false) {
      lastError = createHttpError(
        `cloudtentacles 账号 ${sourceKey} 已停用`,
        { statusCode: 409, errorCode: "kuaishou_cloud_source_disabled" }
      );
      continue;
    }

    if (!session) {
      lastError = createHttpError(
        `cloudtentacles 账号 ${sourceKey} 没有可用 token`,
        { statusCode: 409, errorCode: "kuaishou_cloud_missing_cloud_token" }
      );
      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: normalizeCloudtentaclesDeviceId(
        session.deviceId || source.deviceId
      ),
      deviceType: normalizeCloudtentaclesDeviceType(
        session.deviceType ?? source.deviceType
      ),
      // 透传给 http-client / 错误包装，便于定位跨账号问题
      sourceKey,
      resolvedSourceKey: sourceKey,
      accountLabel: String(source.label || sourceKey).trim() || sourceKey,
    };
  }

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