"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { useStigmer } from "../hooks";
import { useActiveOrgSlug } from "../organization/OrgProvider";
import { useFetch } from "../internal/useFetch";
const DEFAULT_PAGE_SIZE = 30;
const EPOCH = new Date(0);
/**
 * Fetches recent activity via the unified `listRecentActivity` RPC,
 * which returns a merged, time-sorted list of the caller's most
 * recent sessions and workflow executions in a single call.
 *
 * The server handles:
 * - FGA authorization filtering (or org-scoped fast path)
 * - Cross-collection merge-sort by `statusAudit.updatedAt`
 * - Fallback to `specAudit.createdAt` for documents without status updates
 * - Pagination / trimming to the requested page size
 */
export function useRecentActivity(options) {
    const pageSize = options?.pageSize ?? DEFAULT_PAGE_SIZE;
    const stigmer = useStigmer();
    const org = useActiveOrgSlug();
    const { data, isLoading, error, refetch } = useFetch(() => stigmer.activity
        .listRecentActivity({ pageSize, org })
        .then((resp) => resp.entries.map(normalizeEntry)), [stigmer, pageSize, org], [], { cacheKey: `recent-activity:${org}` });
    const [optimistic, setOptimistic] = useState([]);
    const prevDataRef = useRef(data);
    useEffect(() => {
        if (data !== prevDataRef.current) {
            prevDataRef.current = data;
            if (optimistic.length > 0) {
                setOptimistic([]);
            }
        }
    }, [data, optimistic.length]);
    const entries = useMemo(() => {
        if (optimistic.length === 0)
            return data;
        const serverIds = new Set(data.map((e) => e.id));
        const pending = optimistic.filter((e) => !serverIds.has(e.id));
        return pending.length > 0 ? [...pending, ...data] : data;
    }, [data, optimistic]);
    const prependOptimistic = useCallback((input) => {
        setOptimistic((prev) => {
            if (prev.some((e) => e.id === input.id))
                return prev;
            const entry = {
                id: input.id,
                type: input.type,
                subject: input.subject,
                updatedAt: new Date(),
            };
            return [entry, ...prev];
        });
    }, []);
    return { entries, isLoading, error, refetch, prependOptimistic };
}
function normalizeEntry(entry) {
    const updatedAt = entry.updatedAt
        ? timestampDate(entry.updatedAt)
        : EPOCH;
    return {
        id: entry.id,
        type: entry.type === "session" ? "session" : "workflow_execution",
        subject: entry.subject || (entry.type === "session" ? "Untitled session" : "Untitled execution"),
        updatedAt: updatedAt.getTime() > 0 ? updatedAt : EPOCH,
        status: entry.status || undefined,
    };
}
//# sourceMappingURL=useRecentActivity.js.map