import { usePaginatedDataTable, type PaginatedDataTableConfig } from './use-paginated-data-table';
import { usePivotMembership, type PivotMembershipConfig } from './use-pivot-membership';

export interface RelationshipPivotConfig<TLinked, TCandidate> {
  readonly linkedListConfig: PaginatedDataTableConfig<TLinked>;
  readonly candidatesListConfig: PaginatedDataTableConfig<TCandidate>;
  readonly pivotMembershipConfig: PivotMembershipConfig;
}

/**
 * Orchestrator preset for the many-to-many manager case. Composes:
 *
 *  - `usePaginatedDataTable<TLinked>` for the outer (linked) table
 *  - `usePaginatedDataTable<TCandidate>` for the candidates dialog table
 *  - `usePivotMembership<TPivot>` for the linkedIds set + link/unlink ops
 *
 * Side-effect coordination: every successful `link`/`unlink` automatically
 * triggers `linked.refetch()` so the outer table reflects the new state.
 *
 * Hosts that need finer-grained control can compose the three primitives by
 * hand instead of using this orchestrator.
 */
export function useRelationshipPivot<
  TLinked,
  TCandidate,
  TPivot extends Record<string, unknown> = Record<string, unknown>,
>(config: RelationshipPivotConfig<TLinked, TCandidate>) {
  const linked = usePaginatedDataTable<TLinked>(config.linkedListConfig);
  const candidates = usePaginatedDataTable<TCandidate>(config.candidatesListConfig);
  const membership = usePivotMembership<TPivot>(config.pivotMembershipConfig);

  async function init(): Promise<void> {
    await Promise.all([linked.refetch(), membership.refresh()]);
  }

  async function link(childIds: string[]): Promise<void> {
    await membership.link(childIds);
    await linked.refetch();
  }

  async function unlink(childIds: string[]): Promise<void> {
    await membership.unlink(childIds);
    await linked.refetch();
  }

  return {
    linked,
    candidates,
    membership: {
      linkedIds: membership.linkedIds,
      loading: membership.loading,
      refresh: membership.refresh,
      link,
      unlink,
    },
    init,
  };
}

export type RelationshipPivot<TLinked, TCandidate> = ReturnType<
  typeof useRelationshipPivot<TLinked, TCandidate>
>;
