import { apiRequest } from './api.js'

export const NOTIFICATION_STATE_BATCH_SIZE = 100

function normalizeStateItem(item) {
  const notificationId = String(item?.notification_id || item?.notificationId || '').trim()
  if (!notificationId) {
    return null
  }

  return {
    notification_id: notificationId,
    read: Boolean(item?.read),
    hidden: Boolean(item?.hidden),
    context_json: item?.context_json && typeof item.context_json === 'object'
      ? item.context_json
      : {}
  }
}

export function chunkNotificationStatePatches(states = [], batchSize = NOTIFICATION_STATE_BATCH_SIZE) {
  const size = Math.max(1, Number(batchSize) || NOTIFICATION_STATE_BATCH_SIZE)
  const chunks = []

  for (let index = 0; index < states.length; index += size) {
    chunks.push(states.slice(index, index + size))
  }

  return chunks
}

export async function fetchNotificationStates() {
  const payload = await apiRequest('/notification-states')
  return Array.isArray(payload?.states) ? payload.states : []
}

export async function patchNotificationStates(states = []) {
  const normalizedStates = (Array.isArray(states) ? states : [])
    .map(normalizeStateItem)
    .filter(Boolean)

  if (!normalizedStates.length) {
    return []
  }

  let latestStates = []
  for (const batch of chunkNotificationStatePatches(normalizedStates)) {
    const payload = await apiRequest('/notification-states', {
      method: 'POST',
      body: JSON.stringify({ states: batch })
    })
    latestStates = Array.isArray(payload?.states) ? payload.states : latestStates
  }

  return latestStates
}
