import fs from 'fs';
import path from 'path';

/** backend/ 디렉터리 (package.json 기준) */
export function getBackendRoot(): string {
  return path.resolve(__dirname, '../..');
}

/** EENE_Dashboard_0608 루트 */
export function getProjectRoot(): string {
  return path.resolve(getBackendRoot(), '..');
}

export function getDataDir(): string {
  return path.join(getProjectRoot(), 'data');
}

export function getPostgresDataDir(): string {
  return path.join(getDataDir(), 'postgres');
}

export function getSeedDir(): string {
  return path.join(getDataDir(), 'seed');
}

/** HR 원본 JSON — seed·import 공통 (프로젝트 내부 data/seed/) */
export function getHrSeedPath(): string {
  const configured = process.env.HR_DATA_PATH?.trim();
  if (configured) {
    return path.isAbsolute(configured)
      ? configured
      : path.resolve(getBackendRoot(), configured);
  }
  return path.join(getSeedDir(), 'hr-data.json');
}

export function getUploadDir(): string {
  const configured = process.env.UPLOAD_DIR?.trim();
  if (configured) {
    return path.isAbsolute(configured)
      ? configured
      : path.resolve(getBackendRoot(), configured);
  }
  return path.join(getProjectRoot(), 'uploads');
}

export function getTeamUploadDir(): string {
  return path.join(getUploadDir(), 'team');
}

/** 서버 기동 시 data·uploads 등 로컬 영구 저장 폴더 생성 */
export function ensureProjectDataDirs(): void {
  for (const dir of [
    getDataDir(),
    getPostgresDataDir(),
    getSeedDir(),
    getUploadDir(),
    getTeamUploadDir(),
  ]) {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`📁 Created: ${dir}`);
    }
  }
}
