// API route: GET /api/accounts — a paged, sorted, filtered slice of a dataset.
//
// This is the server half of the DataTable `load` contract. The table sends
// page, pageSize, sortKey, sortDirection and query, and expects `rows` for
// that page plus `total` for the whole matching set. The total has to come
// from here: the table only ever sees one page and cannot count the rest.
import type { Context } from "@wrnexus/core";

interface Account {
  id: number;
  name: string;
  plan: string;
  owner: string;
  seats: number;
  renewsOn: string;
}

const PLANS = ["Scale", "Team", "Enterprise", "Starter"];
const OWNERS = ["A. Okafor", "R. Silva", "M. Chen", "J. Dubois", "P. Novak"];
const NAMES = [
  "Northwind",
  "Acme Industrial",
  "Globex",
  "Initech",
  "Umbrella",
  "Stark Labs",
  "Wayne Foods",
  "Soylent",
  "Hooli",
  "Vehement",
  "Massive Dynamic",
  "Cyberdyne",
  "Tyrell",
  "Aperture",
  "Black Mesa",
  "Oceanic",
  "Weyland",
  "Gringotts",
  "Duff Brewing",
  "Prestige Worldwide",
  "Bluth Company",
  "Pied Piper",
];

// Deterministic so paging is stable across requests.
const ACCOUNTS: Account[] = NAMES.map((name, index) => ({
  id: index + 1,
  name,
  plan: PLANS[index % PLANS.length]!,
  owner: OWNERS[index % OWNERS.length]!,
  seats: ((index * 13) % 240) + 4,
  renewsOn: new Date(Date.UTC(2026, index % 12, ((index * 5) % 27) + 1)).toISOString().slice(0, 10),
}));

export function GET(ctx: Context): Response {
  const params = ctx.url.searchParams;
  const page = Math.max(1, Number(params.get("page")) || 1);
  const pageSize = Math.min(100, Math.max(1, Number(params.get("pageSize")) || 10));
  const query = (params.get("query") ?? "").trim().toLowerCase();
  const sortKey = params.get("sortKey") ?? "";
  const descending = params.get("sortDirection") === "desc";

  let matched = ACCOUNTS;
  if (query) {
    matched = matched.filter((account) =>
      [account.name, account.plan, account.owner, account.renewsOn].some((field) =>
        field.toLowerCase().includes(query),
      ),
    );
  }

  if (sortKey) {
    const direction = descending ? -1 : 1;
    matched = [...matched].sort((left, right) => {
      const a = left[sortKey as keyof Account];
      const b = right[sortKey as keyof Account];
      if (typeof a === "number" && typeof b === "number") return (a - b) * direction;
      return String(a).localeCompare(String(b)) * direction;
    });
  }

  const start = (page - 1) * pageSize;

  return Response.json({
    rows: matched.slice(start, start + pageSize),
    total: matched.length,
    page,
    pageSize,
  });
}
