import neo4j from "neo4j-driver";
import type { Driver, Session } from "neo4j-driver";
import { env } from "./env.js";

// Neo4j driver 创建为惰性初始化：未配置 NEO4J_URL / NEO4J_PASSWORD 时
// driver 保持 null，服务仍可正常启动。所有依赖 Neo4j 的查询在
// driver 为 null 时返回空结果或抛出可控错误，不会阻塞主流程。
let driver: Driver | null = null;

try {
  if (env.NEO4J_URL && env.NEO4J_PASSWORD) {
    driver = neo4j.driver(
      env.NEO4J_URL,
      neo4j.auth.basic("neo4j", env.NEO4J_PASSWORD),
      // 连接超时 3s：Neo4j 不可用时快速失败，避免拖慢 HTTP 响应
      { connectionTimeout: 3000, maxConnectionLifetime: 60_000 },
    );
  }
} catch (err) {
  console.warn(
    "Neo4j driver init failed, running without Neo4j:",
    err instanceof Error ? err.message : String(err),
  );
  driver = null;
}

export function getNeo4jSession(): Session | null {
  if (!driver) {
    return null;
  }
  return driver.session();
}

export async function closeNeo4j(): Promise<void> {
  if (driver) {
    await driver.close();
  }
}
