import * as plugins from './plugins.js';

// Code/asset paths (not affected by baseDir)
export const packageDir = plugins.path.join(
  plugins.smartpath.get.dirnameFromImportMetaUrl(import.meta.url),
  '../'
);
export const distServe = plugins.path.join(packageDir, './dist_serve');

// Default base for all dcrouter data (always user-writable)
export const dcrouterHomeDir = plugins.path.join(plugins.os.homedir(), '.serve.zone', 'dcrouter');

// Configure data directory with environment variable or default to ~/.serve.zone/dcrouter/data
const DEFAULT_DATA_PATH = plugins.path.join(dcrouterHomeDir, 'data');
export const dataDir = process.env.DATA_DIR
  ? process.env.DATA_DIR
  : DEFAULT_DATA_PATH;

// Default TsmDB path for CacheDb
export const defaultTsmDbPath = plugins.path.join(dcrouterHomeDir, 'tsmdb');

// DNS records directory (only surviving MTA directory reference)
export const dnsRecordsDir = plugins.path.join(dataDir, 'dns');

/**
 * Resolve all data paths from a given baseDir.
 * When no baseDir is provided, falls back to ~/.serve.zone/dcrouter.
 * Specific overrides (e.g. DATA_DIR env) take precedence.
 */
export function resolvePaths(baseDir?: string) {
  const root = baseDir ?? plugins.path.join(plugins.os.homedir(), '.serve.zone', 'dcrouter');
  const resolvedDataDir = process.env.DATA_DIR ?? plugins.path.join(root, 'data');
  return {
    dcrouterHomeDir: root,
    dataDir: resolvedDataDir,
    defaultTsmDbPath: plugins.path.join(root, 'tsmdb'),
    dnsRecordsDir: plugins.path.join(resolvedDataDir, 'dns'),
  };
}

/**
 * Ensure only the data directories that are actually used exist.
 */
export function ensureDataDirectories(resolvedPaths: ReturnType<typeof resolvePaths>) {
  plugins.fsUtils.ensureDirSync(resolvedPaths.dataDir);
  plugins.fsUtils.ensureDirSync(resolvedPaths.dnsRecordsDir);
}

/**
 * Legacy wrapper — delegates to ensureDataDirectories with module-level defaults.
 */
export function ensureDirectories() {
  ensureDataDirectories(resolvePaths());
}
