import type { Release, Software } from './interfaces/software.interface'

const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000

export function isNew(createdAt: string): boolean {
  return (Date.now() - new Date(createdAt).getTime()) < SEVEN_DAYS_MS
}

export function getDefaultImageUrl(sw: Software): string | null {
  if (sw.images?.length) {
    const def = sw.images.find(i => i.isDefault)
    return def?.url ?? sw.images[0]?.url ?? null
  }
  return sw.imageUrl ?? null
}

export function filterStableReleases(releases: Release[]): Release[] {
  return releases
    .filter(r => !r.version.startsWith('dev-'))
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
}

export function filterDevReleases(releases: Release[]): Release[] {
  return releases
    .filter(r => r.version.startsWith('dev-'))
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
}

export function getLatestStable(releases: Release[]): Release | undefined {
  return filterStableReleases(releases)[0]
}
