import {
  ArticleModel,
} from "../types/models";

export function createInList(list: ArticleModel[], a: ArticleModel) {
  return [...list, a];
}

export function readInList(list: ArticleModel[], index: number) {
  if (index < 0 || index >= list.length) {
    // Soft fallback
    return undefined;
  }
  return list[index];
}

export function updateInList(list: ArticleModel[], a: ArticleModel) {
  return list.map(x => (x._id === a._id ? a : x));
}

export function deleteInList(list: ArticleModel[], id: string) {
  return list.filter(x => x._id !== id);
}

// Map helpers
export function createById(
  map: Record<string, ArticleModel>,
  a: ArticleModel
) {
  if (!a._id) {
    // Soft mode: ignore create, return unchanged
    return map;
  }

  if (map[a._id]) {
    // Soft mode: do not replace existing
    return map;
  }

  return { ...map, [a._id]: a };
}

export function readById(
  map: Record<string, ArticleModel>,
  id: string
) {
  if (!id) return undefined;
  return map[id];
}

export function updateById(
  map: Record<string, ArticleModel>,
  a: ArticleModel
) {
  if (!a._id) {
    // Cannot update without ID
    return map;
  }

  if (!map[a._id]) {
    // ID does not exist → soft mode: do nothing
    return map;
  }

  return { ...map, [a._id]: a };
}

export function deleteById(
  map: Record<string, ArticleModel>,
  id: string
) {
  const { [id]: _, ...rest } = map;
  return rest;
}
