/**
 * Source-of-rows composable for `DataTableCard`.
 *
 * Resolves the row array from one of three sources, in priority order:
 *
 *   1. `searchRoute` — remote fetch. Currently a STUB that logs a debug
 *      message and returns `[]`. Real HTTP integration (axios) lands in
 *      a follow-up task.
 *   2. `listKey` — nested array read off `item[listKey]`.
 *   3. `listData` — inline static rows on the card.
 *
 * Falls back to an empty array when no source is configured.
 *
 * Exposed as a composable so tests can intercept the row source
 * without mocking the network layer.
 */
import { computed, type ComputedRef, type Ref } from "vue"
import type { DataTableOptions } from "@/definitions/cards/DataTableCard"

export interface UseDataTableDataOptions {
  listKey: Ref<string | undefined> | ComputedRef<string | undefined>
  listData: Ref<unknown[] | undefined> | ComputedRef<unknown[] | undefined>
  options: Ref<DataTableOptions | undefined> | ComputedRef<DataTableOptions | undefined>
  item: Ref<Record<string, unknown>> | ComputedRef<Record<string, unknown>>
}

export interface UseDataTableDataReturn {
  rows: ComputedRef<Record<string, unknown>[]>
}

export function useDataTableData(
  opts: UseDataTableDataOptions,
): UseDataTableDataReturn {
  const rows = computed<Record<string, unknown>[]>(() => {
    const i = opts.item.value
    const o = opts.options.value
    const listKey = opts.listKey.value
    const listData = opts.listData.value

    if (o?.searchRoute) {
      // eslint-disable-next-line no-console
      console.debug(
        "[DataTableCard] searchRoute fetch is stubbed; returning empty rows.",
        o.searchRoute,
      )
      return []
    }

    if (listKey) {
      const raw = i[listKey]
      if (Array.isArray(raw)) {
        return raw as Record<string, unknown>[]
      }
      return []
    }

    if (Array.isArray(listData)) {
      return listData as Record<string, unknown>[]
    }

    return []
  })

  return { rows }
}
