import type { SubsonicAlbum } from '../../api/subsonicTypes';
import { dedupeById } from '../dedupeById';
import { isOfflineBrowseActive } from '../offline/offlineBrowseMode';
import { loadOfflineAlbumCatalogChunk } from '../offline/offlineAlbumBrowseCatalog';
import type { AlbumBrowseQuery } from './albumBrowseTypes';
import { fetchLocalAlbumCatalogChunk } from './albumBrowseLoad';

export type AlbumCatalogChunk = {
  albums: SubsonicAlbum[];
  hasMore: boolean;
};

export function mergeAlbumCatalogChunk(
  prev: SubsonicAlbum[],
  chunk: AlbumCatalogChunk,
  append: boolean,
): { albums: SubsonicAlbum[]; offset: number } {
  if (!append) {
    return { albums: chunk.albums, offset: chunk.albums.length };
  }
  const merged = dedupeById([...prev, ...chunk.albums]);
  return { albums: merged, offset: merged.length };
}

/** Local-index or offline-bytes catalog chunk for the albums grid. */
export async function fetchAlbumBrowseCatalogChunk(
  serverId: string,
  query: AlbumBrowseQuery,
  offset: number,
  chunkSize: number,
  starredOverrides: Record<string, boolean>,
): Promise<AlbumCatalogChunk | null> {
  if (isOfflineBrowseActive()) {
    return loadOfflineAlbumCatalogChunk(
      serverId,
      query,
      offset,
      chunkSize,
      starredOverrides,
    );
  }
  return fetchLocalAlbumCatalogChunk(serverId, query, offset, chunkSize);
}
