/**
 * 버전 보존 정책 순수 로직
 *
 * Firebase 의존 없음 → 단위 테스트 용이
 */

import { VersionInfo, VersionRetentionConfig } from './types/version';

/**
 * 삭제 대상 버전 ID 목록 반환
 *
 * 보존 조건:
 *  1. 최신 maxVersions개
 *  2. maxAgeDays 이내 생성된 버전
 *
 * 두 조건 모두 해당하지 않는 버전만 삭제 대상
 */
export function getVersionsToDelete(
  versions: VersionInfo[],
  config: VersionRetentionConfig,
  now: Date = new Date()
): string[] {
  if (versions.length === 0) return [];

  // createdAt 기준 내림차순 정렬 (최신 먼저)
  const sorted = [...versions].sort(
    (a, b) => b.createdAt.getTime() - a.createdAt.getTime()
  );

  const cutoffTime = now.getTime() - config.maxAgeDays * 24 * 60 * 60 * 1000;

  const toDelete: string[] = [];

  sorted.forEach((v, index) => {
    const isWithinCountLimit = index < config.maxVersions;
    const isWithinAgeLimit = v.createdAt.getTime() >= cutoffTime;

    if (!isWithinCountLimit && !isWithinAgeLimit) {
      toDelete.push(v.id);
    }
  });

  return toDelete;
}
