import {
  makeProjectMajorKey,
  resolveScaleRowMajorDictId,
  resolveScaleRowProjectIndex
} from '@/lib/pricingScaleLink'

const PROJECT_PATH_PREFIX = 'project-'
const PROJECT_ROW_ID_SEPARATOR = '::'

export const normalizeScaleProjectCount = (value: unknown) => {
  const parsed = Number(value)
  if (!Number.isFinite(parsed)) return 1
  return Math.max(1, Math.floor(parsed))
}

export const buildScaleProjectGroupPathKey = (projectIndex: number) => `${PROJECT_PATH_PREFIX}${projectIndex}`

export const buildScopedScaleRowId = (
  isMutipleService: boolean,
  projectIndex: number,
  majorId: string
) => (isMutipleService ? `${projectIndex}${PROJECT_ROW_ID_SEPARATOR}${majorId}` : majorId)

export const inferScaleProjectCountFromRows = <TRow>(
  rows: Array<Partial<TRow>> | undefined,
  isMutipleService: boolean
) => {
  if (!isMutipleService) return 1
  let maxProjectIndex = 1
  for (const row of rows || []) {
    maxProjectIndex = Math.max(maxProjectIndex, resolveScaleRowProjectIndex(row))
  }
  return maxProjectIndex
}

export const getScaleProjectMajorKeyFromRow = <TRow>(row: Partial<TRow> | undefined) => {
  if (!row) return ''
  const majorDictId = resolveScaleRowMajorDictId(row)
  if (!majorDictId) return ''
  return makeProjectMajorKey(resolveScaleRowProjectIndex(row), majorDictId)
}
