/**
 * Flock 登录凭据上下文：客户账密（ALS）优先于环境变量
 */
import { AsyncLocalStorage } from "node:async_hooks";
import type { FlockLoginCredentials } from "@/lib/flock/env";

export type FlockLoginSource = "customer" | "env" | null;

type Store = {
  login: FlockLoginCredentials | null;
  source: FlockLoginSource;
};

const flockLoginAls = new AsyncLocalStorage<Store>();

function envFlockLogin(): FlockLoginCredentials | null {
  const email = process.env.FLOCK_LOGIN_EMAIL?.trim() ?? "";
  const password = process.env.FLOCK_LOGIN_PASSWORD?.trim() ?? "";
  if (!email || !password) {
    return null;
  }
  return { email, password };
}

/** 在查价 job 内绑定客户/环境凭据 */
export function runWithFlockLoginContext<T>(
  login: FlockLoginCredentials | null,
  source: FlockLoginSource,
  fn: () => Promise<T>,
): Promise<T> {
  return flockLoginAls.run({ login, source }, fn);
}

export function getEffectiveFlockLogin(): FlockLoginCredentials | null {
  const store = flockLoginAls.getStore();
  if (store?.login) {
    return store.login;
  }
  return envFlockLogin();
}

export function hasEffectiveFlockLogin(): boolean {
  return getEffectiveFlockLogin() !== null;
}

export function getFlockLoginSource(): FlockLoginSource {
  const store = flockLoginAls.getStore();
  if (store?.login) {
    return store.source;
  }
  return envFlockLogin() ? "env" : null;
}

/** 客户账密必须强制官网登录，禁止吃共享 storage / 错号会话 */
export function mustForceFlockAccountLogin(): boolean {
  return getFlockLoginSource() === "customer";
}
