export interface NormalizedKpiFilters {
  kpiCategory?: string
  kpiFilter?: string
  allocatedProgramId?: number
  pendingProgramId?: number
  swapPreferredProgramId?: number
  swapDemandPreferredProgramId?: number
  defaulterStatus?: string
}

/**
 * Decodes dynamic KPI shortcut strings sent from the frontend dashboard tiles
 * into concrete filter fields understood by both the report Postgres function
 * and the registration service TypeORM path.
 *
 * Examples:
 *   kpiCategory='program_42'          → kpiCategory='blessed', allocatedProgramId=42
 *   kpiFilter='program_42'            → kpiCategory='blessed', kpiFilter='approvedSeekers', allocatedProgramId=42
 *   kpiFilter='regPending_program_42' → kpiFilter='regPending', pendingProgramId=42
 *   kpiFilter='swapRequests_program_42' → kpiFilter='swapRequests', swapPreferredProgramId=42
 *   kpiFilter='onHold_program_42'     → kpiFilter='onHold', swapDemandPreferredProgramId=42
 *   kpiCategory='defaulter'           → kpiCategory='registrations', defaulterStatus='defaulter'
 */
export function normalizeKpiPatterns(
  kpiCategory: string | undefined,
  kpiFilter: string | undefined,
): NormalizedKpiFilters {
  if (!kpiCategory && !kpiFilter) return {}

  const out: NormalizedKpiFilters = { kpiCategory, kpiFilter }

  if (out.kpiCategory === 'defaulter') {
    out.defaulterStatus = 'defaulter'
    out.kpiCategory = 'registrations'
  }

  const categoryProgramMatch = out.kpiCategory?.match(/^program_(\d+)$/)
  if (categoryProgramMatch) {
    out.allocatedProgramId = parseInt(categoryProgramMatch[1])
    out.kpiCategory = 'blessed'
    if (out.kpiFilter?.match(/^program_\d+$/)) out.kpiFilter = 'approvedSeekers'
    return out
  }

  const filterProgramMatch = out.kpiFilter?.match(/^program_(\d+)$/)
  if (filterProgramMatch) {
    out.allocatedProgramId = parseInt(filterProgramMatch[1])
    out.kpiFilter = 'approvedSeekers'
    out.kpiCategory = 'blessed'
    return out
  }

  const regPendingMatch = out.kpiFilter?.match(/^regPending_program_(\d+)$/)
  if (regPendingMatch) {
    out.pendingProgramId = parseInt(regPendingMatch[1])
    out.kpiFilter = 'regPending'
    return out
  }

  const swapReqMatch = out.kpiFilter?.match(/^swapRequests_program_(\d+)$/)
  if (swapReqMatch) {
    out.swapPreferredProgramId = parseInt(swapReqMatch[1])
    out.kpiFilter = 'swapRequests'
    return out
  }

  const onHoldMatch = out.kpiFilter?.match(/^onHold_program_(\d+)$/)
  if (onHoldMatch) {
    out.swapDemandPreferredProgramId = parseInt(onHoldMatch[1])
    out.kpiFilter = 'onHold'
    return out
  }

  return out
}

/** Extracts the numeric program ID from a `program_<id>` KPI key. Returns null if the key doesn't match. */
export function parseProgramIdFromKpiKey(key: string | undefined): number | null {
  if (!key) return null
  const match = key.match(/^program_(\d+)$/)
  return match ? parseInt(match[1]) : null
}
