import { computed, signal, type Signal } from '@angular/core';
import type { PaginationState } from '@tanstack/angular-table';
import { DEFAULT_PAGE_SIZE } from '../../../components/data-table/types';

export interface TablePaginationAtom {
  readonly state: Signal<PaginationState>;
  readonly offset: Signal<number>;
  readonly limit: Signal<number>;
  set(s: PaginationState): void;
}

/**
 * Atom: pagination state. Single responsibility — owns a `PaginationState`
 * signal and exposes derived `offset`/`limit` accessors typically needed when
 * building a server query.
 */
export function useTablePagination(
  defaultPageSize: number = DEFAULT_PAGE_SIZE,
): TablePaginationAtom {
  const state = signal<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize });
  const offset = computed(() => state().pageIndex * state().pageSize);
  const limit = computed(() => state().pageSize);

  return {
    state: state.asReadonly(),
    offset,
    limit,
    set: (s: PaginationState) => state.set(s),
  };
}
