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

export type MothershipLogin = {
  email: string;
  password: string;
};

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

type Store = {
  login: MothershipLogin | null;
  source: MothershipLoginSource;
};

const mothershipLoginAls = new AsyncLocalStorage<Store>();

function envMothershipLogin(): MothershipLogin | null {
  const email = process.env.MOTHERSHIP_EMAIL?.trim() ?? "";
  const password = process.env.MOTHERSHIP_PASSWORD?.trim() ?? "";
  if (!email || !password) {
    return null;
  }
  return { email, password };
}

export function runWithMothershipLoginContext<T>(
  login: MothershipLogin | null,
  source: MothershipLoginSource,
  fn: () => Promise<T>,
): Promise<T> {
  return mothershipLoginAls.run({ login, source }, fn);
}

export function getEffectiveMothershipLogin(): MothershipLogin | null {
  const store = mothershipLoginAls.getStore();
  if (store?.login) {
    return store.login;
  }
  return envMothershipLogin();
}

export function hasEffectiveMothershipLogin(): boolean {
  return getEffectiveMothershipLogin() !== null;
}

export function getMothershipLoginSource(): MothershipLoginSource {
  const store = mothershipLoginAls.getStore();
  if (store?.login) {
    return store.source;
  }
  return envMothershipLogin() ? "env" : null;
}
