import { getAdminQueues, getAdminQueueJobs } from "$lib/services";

const LIMIT = 25;

export async function load({ fetch, cookies, url }) {
  const token = cookies.get("session_token") || "";
  const queues = await getAdminQueues(fetch, token).catch(() => []);

  const queueParam = url.searchParams.get("queue") ?? queues[0]?.name ?? null;
  const status = url.searchParams.get("status") ?? null;
  const offset = parseInt(url.searchParams.get("offset") ?? "0") || 0;

  let jobs: Awaited<ReturnType<typeof getAdminQueueJobs>> = [];
  let total = 0;

  if (queueParam) {
    jobs = await getAdminQueueJobs(
      queueParam,
      status ?? undefined,
      LIMIT,
      offset,
      fetch,
      token,
    ).catch(() => []);

    const queueInfo = queues.find((q) => q.name === queueParam);
    if (queueInfo) {
      const { waiting, active, completed, failed, delayed } = queueInfo.counts;
      const counts: Record<string, number> = { waiting, active, completed, failed, delayed };
      total = status ? (counts[status] ?? 0) : Object.values(counts).reduce((a, b) => a + b, 0);
    }
  }

  return { queues, queue: queueParam, status, jobs, total, offset, limit: LIMIT };
}
