/**
 * The pure decisions behind page-at-a-time list accumulation.
 *
 * Ten hooks each re-derived these two answers inline, and the copies had
 * already drifted: three read `pagination.current_page` as a fallback (a key
 * `ApiResponse::paginated()` does not emit), and several took the page number
 * from their own `currentPage` state rather than from the response — which
 * attributes a page to the wrong request while a fetch is in flight and is how
 * the same page gets merged twice.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";

import {
  appendUniqueById,
  hasMoreAfter,
  responsePage,
} from "@/features/shared/pagedList";
import type { ApiPagination } from "@/lib/api/types";

const meta = (page: number, totalPages: number): ApiPagination => ({
  page,
  limit: 10,
  total: totalPages * 10,
  total_pages: totalPages,
});

describe("responsePage", () => {
  test("prefers the response's own page over the caller's guess", () => {
    assert.equal(responsePage(meta(2, 5), 99), 2);
  });

  test("falls back when the endpoint sent no pagination block", () => {
    assert.equal(responsePage(undefined, 3), 3);
  });

  test("page 1 is not mistaken for missing", () => {
    // `||` would have skipped a legitimate 0; `??` is what the code uses.
    assert.equal(responsePage({ ...meta(1, 2), page: 0 }, 7), 0);
  });

  test("reads Laravel's current_page when that is what arrived", () => {
    const laravelShape = {
      current_page: 4,
      limit: 10,
      total: 80,
      total_pages: 8,
    } as unknown as ApiPagination;
    assert.equal(responsePage(laravelShape, 1), 4);
  });
});

describe("hasMoreAfter", () => {
  test("with metadata, compares the page against total_pages", () => {
    assert.equal(hasMoreAfter(meta(1, 3), 10, 10, 1), true);
    assert.equal(hasMoreAfter(meta(3, 3), 10, 10, 3), false);
  });

  test("a single-page result reports no more", () => {
    assert.equal(hasMoreAfter(meta(1, 1), 4, 10, 1), false);
  });

  test("without metadata, a full page means there may be another", () => {
    assert.equal(hasMoreAfter(undefined, 10, 10, 1), true);
  });

  test("without metadata, a short page is the end", () => {
    assert.equal(hasMoreAfter(undefined, 6, 10, 1), false);
  });

  test("without metadata, an empty page is the end", () => {
    assert.equal(hasMoreAfter(undefined, 0, 10, 2), false);
  });

  test("metadata wins over the row count — a short last page still ends", () => {
    assert.equal(hasMoreAfter(meta(2, 2), 10, 10, 2), false);
  });
});

describe("appendUniqueById", () => {
  test("appends rows that are new", () => {
    assert.deepEqual(
      appendUniqueById([{ id: 1 }, { id: 2 }], [{ id: 3 }]),
      [{ id: 1 }, { id: 2 }, { id: 3 }]
    );
  });

  test("drops a row the list already holds", () => {
    assert.deepEqual(
      appendUniqueById([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }]),
      [{ id: 1 }, { id: 2 }, { id: 3 }]
    );
  });

  test("keeps the existing row, not the incoming duplicate", () => {
    const result = appendUniqueById(
      [{ id: 1, name: "first" }],
      [{ id: 1, name: "second" }]
    );
    assert.deepEqual(result, [{ id: 1, name: "first" }]);
  });

  test("works with string ids", () => {
    assert.deepEqual(
      appendUniqueById([{ id: "a" }], [{ id: "a" }, { id: "b" }]),
      [{ id: "a" }, { id: "b" }]
    );
  });

  test("does not mutate the list it was given", () => {
    const previous = [{ id: 1 }];
    appendUniqueById(previous, [{ id: 2 }]);
    assert.deepEqual(previous, [{ id: 1 }]);
  });
});

/* ───────────────────────────────────────────────────────────────────────────
 * The accumulator's state machine.
 *
 * `nextPagedState` is the whole of what the hook does; the hook only wires it to
 * `useState`. Each block below is one of the seven behaviours paging has to get
 * right, driven as a sequence of inputs the way React would deliver them.
 * ─────────────────────────────────────────────────────────────────────────── */

import {
  initialPagedState,
  nextPagedState,
  type PagedState,
} from "@/features/shared/pagedList";

interface Row {
  id: number;
  name: string;
}

const rows = (...ids: number[]): Row[] =>
  ids.map((id) => ({ id, name: `row-${id}` }));

const envelope = (
  data: Row[],
  page: number,
  totalPages: number,
  limit = 2
) => ({
  key: "success",
  msg: "",
  code: 200,
  response_status: { error: false, validation_errors: {} },
  data,
  meta: { pagination: { page, limit, total: totalPages * limit, total_pages: totalPages } },
});

/** Apply one render's worth of input, returning the state the hook would report. */
function step(
  state: PagedState<Row>,
  input: Parameters<typeof nextPagedState<Row>>[1]
): PagedState<Row> {
  return nextPagedState(state, input) ?? state;
}

const ids = (state: PagedState<Row>) => state.items.map((row) => row.id);

describe("paging: a filter change while a request is in flight", () => {
  test("the previous filter's rows are dropped in the same step", () => {
    let state = step(initialPagedState<Row>("search=a"), {
      resetSignature: "search=a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2]);

    /* The filter changes. React Query has not answered yet, so the response
       still holds the old filter's page 1 and `isFetching` is true. */
    state = step(state, {
      resetSignature: "search=b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
    });
    assert.deepEqual(ids(state), [], "no frame of the old filter's rows");
    assert.equal(state.hasMore, true, "the new filter may have more");
    assert.deepEqual(state.merged, [], "nothing is merged for the new filter");
  });

  test("the new filter's first page then lands normally", () => {
    let state = step(initialPagedState<Row>("search=a"), {
      resetSignature: "search=a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "search=b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "search=b",
      response: envelope(rows(9, 8), 1, 1),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [9, 8]);
    assert.equal(state.hasMore, false);
  });

  test("a filter change with no request in flight still clears", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    /* Same response object, new signature, not fetching: the signature alone
       must clear, or the old rows would be attributed to the new filter. */
    state = step(state, {
      resetSignature: "b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2], "page 1 of the new filter replaces");
    assert.deepEqual(state.merged, [1]);
    assert.equal(state.signature, "b");
  });
});

describe("paging: a stale response", () => {
  test("a response arriving while isFetching is true is not merged", () => {
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
    });
    assert.deepEqual(ids(state), []);
  });

  test("page 1's rows are not appended again as if they were page 2", () => {
    // The fault this replaces: the old effects read the *caller's* page state,
    // so advancing to page 2 re-ran them while `response` still held page 1.
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    // Caller advances to page 2; the response has not changed yet.
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2], "page 1 was not doubled");
  });
});

describe("paging: retries", () => {
  test("the same page delivered twice is merged once", () => {
    let state = initialPagedState<Row>("a");
    for (const _ of [0, 1, 2]) {
      state = step(state, {
        resetSignature: "a",
        response: envelope(rows(3, 4), 2, 3),
        isFetching: false,
        limit: 2,
      });
    }
    assert.deepEqual(ids(state), [3, 4]);
    assert.deepEqual(state.merged, [2]);
  });

  test("a failed fetch that clears the response leaves the rows alone", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    const before = ids(state);
    state = step(state, {
      resetSignature: "a",
      response: undefined,
      isFetching: true,
      limit: 2,
    });
    assert.deepEqual(ids(state), before, "a retry in flight is not a reset");
  });

  test("refetching page 1 reloads rather than appends, and reopens later pages", () => {
    let state = initialPagedState<Row>("a");
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(3, 4), 2, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2, 3, 4]);

    // A pull-to-refresh: page 1 again, with a row added at the top.
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(0, 1), 1, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [0, 1], "page 1 replaces the whole list");
    assert.deepEqual(state.merged, [1], "pages 2..n are mergeable again");

    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(2, 3), 2, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [0, 1, 2, 3]);
  });
});

describe("paging: deduplication", () => {
  test("without dedupeById, a row repeated across pages is kept twice", () => {
    // Deliberate: most endpoints have stable ordering and a repeat would mean
    // two genuinely distinct records, so the default must not silently drop one.
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(2, 3), 2, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2, 2, 3]);
  });

  test("with dedupeById, the cross-page repeat is dropped", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
      dedupeById: true,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(2, 3), 2, 3),
      isFetching: false,
      limit: 2,
      dedupeById: true,
    });
    assert.deepEqual(ids(state), [1, 2, 3]);
  });

  test("with dedupeById, a duplicate *within* page 1 is dropped too", () => {
    // `/posts/` does this, which is why the code this replaced deduped page 1
    // against itself.
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 1, 2), 1, 2, 3),
      isFetching: false,
      limit: 3,
      dedupeById: true,
    });
    assert.deepEqual(ids(state), [1, 2]);
  });

  test("dedupeById keeps the first copy, so earlier pages win", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope([{ id: 1, name: "from-page-1" }], 1, 2, 1),
      isFetching: false,
      limit: 1,
      dedupeById: true,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope([{ id: 1, name: "from-page-2" }], 2, 2, 1),
      isFetching: false,
      limit: 1,
      dedupeById: true,
    });
    assert.deepEqual(state.items, [{ id: 1, name: "from-page-1" }]);
  });
});

describe("paging: the last page", () => {
  test("hasMore goes false on the final page", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 2),
      isFetching: false,
      limit: 2,
    });
    assert.equal(state.hasMore, true);
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(3, 4), 2, 2),
      isFetching: false,
      limit: 2,
    });
    assert.equal(state.hasMore, false);
    assert.deepEqual(ids(state), [1, 2, 3, 4]);
  });

  test("a single-page result reports no more immediately", () => {
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1), 1, 1),
      isFetching: false,
      limit: 2,
    });
    assert.equal(state.hasMore, false);
  });

  test("an empty result is not left claiming there is more", () => {
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope([], 1, 1),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), []);
    assert.equal(state.hasMore, false);
  });

  test("without pagination metadata, a short page ends the list", () => {
    const bare = {
      key: "success",
      msg: "",
      code: 200,
      response_status: { error: false, validation_errors: {} },
      data: rows(1),
    };
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: bare,
      isFetching: false,
      limit: 2,
    });
    assert.equal(state.hasMore, false);
  });
});

describe("paging: ordering", () => {
  test("rows keep the order the endpoint sent them, within and across pages", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(7, 3, 9), 1, 2, 3),
      isFetching: false,
      limit: 3,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(1, 8, 2), 2, 2, 3),
      isFetching: false,
      limit: 3,
    });
    assert.deepEqual(
      ids(state),
      [7, 3, 9, 1, 8, 2],
      "no sorting is introduced — the API's ordering is the ordering"
    );
  });

  test("a page arriving out of sequence appends where it lands", () => {
    // Recorded rather than defended: the call sites this replaced behaved the
    // same way, and with one in-flight request at a time it cannot happen.
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(5, 6), 3, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "a",
      response: envelope(rows(3, 4), 2, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(ids(state), [1, 2, 5, 6, 3, 4]);
    assert.deepEqual(state.merged, [1, 3, 2]);
  });

  test("the accumulator never mutates the state it was given", () => {
    const first = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    const snapshot = [...first.items];
    step(first, {
      resetSignature: "a",
      response: envelope(rows(3, 4), 2, 3),
      isFetching: false,
      limit: 2,
    });
    assert.deepEqual(first.items, snapshot);
  });
});

describe("paging: the render-time adjustment settles", () => {
  test("a steady input returns null, so the render does not loop", () => {
    /* One response object, delivered twice — which is what React Query does
       across re-renders. Identity is the signal, so the second delivery is a
       no-op. Building a second equal object here instead would model a
       *refetch*, which must not be a no-op; that is the next test. */
    const response = envelope(rows(1, 2), 1, 3);
    const input = {
      resetSignature: "a",
      response,
      isFetching: false,
      limit: 2,
    };
    const state = step(initialPagedState<Row>("a"), input);
    assert.equal(
      nextPagedState(state, input),
      null,
      "nothing to write, so no re-render is triggered"
    );
  });

  test("a new response object with the same page 1 is a reload, not a no-op", () => {
    const state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    const refetched = nextPagedState(state, {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    assert.notEqual(
      refetched,
      null,
      "a refetch must be applied even when the rows happen to match"
    );
  });

  test("an empty initial state with no response also settles", () => {
    const start = initialPagedState<Row>("a");
    assert.equal(
      nextPagedState(start, {
        resetSignature: "a",
        response: undefined,
        isFetching: true,
        limit: 2,
      }),
      null
    );
  });
});

describe("paging: keepPreviousWhileFetching", () => {
  test("by default a filter change clears the visible rows", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
    });
    state = step(state, {
      resetSignature: "b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
    });
    assert.deepEqual(ids(state), []);
  });

  test("with the option, the previous rows stay until the new page 1 lands", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    state = step(state, {
      resetSignature: "b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    assert.deepEqual(ids(state), [1, 2], "no empty flash in the picker");
    assert.deepEqual(state.merged, [], "but nothing is merged for the new term");
    assert.equal(state.signature, "b");
  });

  test("and the new page 1 replaces them rather than appending", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    state = step(state, {
      resetSignature: "b",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: true,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    state = step(state, {
      resetSignature: "b",
      response: envelope(rows(7, 8), 1, 1),
      isFetching: false,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    assert.deepEqual(ids(state), [7, 8], "the kept rows are not prepended");
    assert.equal(state.hasMore, false);
  });

  test("the option does not keep rows across an empty new result", () => {
    let state = step(initialPagedState<Row>("a"), {
      resetSignature: "a",
      response: envelope(rows(1, 2), 1, 3),
      isFetching: false,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    state = step(state, {
      resetSignature: "b",
      response: envelope([], 1, 1),
      isFetching: false,
      limit: 2,
      keepPreviousWhileFetching: true,
    });
    assert.deepEqual(ids(state), [], "a genuine 'no matches' must show empty");
  });
});
