"use client";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import * as React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
const ACTIVE_TIMER_REVALIDATE_MS = 3e4;
const BASE_ACTIVE_TIMER_KEY = ["staff", "timesheets", "activeTimer"];
const EMPTY_ACTIVE_TIMER = {
  staffMemberId: null,
  entryId: null,
  running: false,
  startedAt: null,
  projectId: null,
  projectName: null,
  projectColor: null,
  notes: null
};
const activeTimesheetTimerQueryKey = () => BASE_ACTIVE_TIMER_KEY;
function getString(value) {
  return typeof value === "string" && value.length > 0 ? value : null;
}
function getErrorMessage(result, fallback) {
  if (result && typeof result === "object") {
    const error = result.error;
    if (typeof error === "string" && error.length > 0) return error;
  }
  return fallback;
}
async function loadCurrentStaffMemberId(staffMemberId) {
  if (staffMemberId) return staffMemberId;
  const selfRes = await apiCall("/api/staff/team-members/self");
  if (!selfRes.ok) {
    throw new Error(getErrorMessage(selfRes.result, "Failed to load current staff member."));
  }
  return selfRes.result?.member?.id ?? null;
}
async function loadProjectDisplay(projectId) {
  const projectRes = await apiCall(
    `/api/staff/timesheets/time-projects?ids=${encodeURIComponent(projectId)}&pageSize=1`
  );
  if (!projectRes.ok) {
    return { projectName: null, projectColor: null };
  }
  const project = projectRes.result?.items?.[0];
  return {
    projectName: getString(project?.name),
    projectColor: getString(project?.color)
  };
}
async function fetchActiveTimesheetTimer(staffMemberId) {
  const memberId = await loadCurrentStaffMemberId(staffMemberId);
  if (!memberId) {
    return EMPTY_ACTIVE_TIMER;
  }
  const entriesRes = await apiCall(
    `/api/staff/timesheets/time-entries?staffMemberId=${encodeURIComponent(memberId)}&running=true&pageSize=50`
  );
  if (!entriesRes.ok) {
    throw new Error(getErrorMessage(entriesRes.result, "Failed to load active timer."));
  }
  const entries = Array.isArray(entriesRes.result?.items) ? entriesRes.result.items : [];
  const active = entries.find((entry) => {
    const startedAt = entry.started_at ?? entry.startedAt;
    const endedAt = entry.ended_at ?? entry.endedAt;
    return startedAt != null && endedAt == null;
  });
  if (!active) {
    return { ...EMPTY_ACTIVE_TIMER, staffMemberId: memberId };
  }
  const projectId = getString(active.time_project_id ?? active.timeProjectId);
  const projectDisplay = projectId ? await loadProjectDisplay(projectId) : { projectName: null, projectColor: null };
  return {
    staffMemberId: memberId,
    entryId: getString(active.id),
    running: true,
    startedAt: getString(active.started_at ?? active.startedAt),
    projectId,
    projectName: projectDisplay.projectName,
    projectColor: projectDisplay.projectColor,
    notes: getString(active.notes)
  };
}
const activeTimesheetTimerQueryOptions = (staffMemberId) => ({
  queryKey: activeTimesheetTimerQueryKey(),
  staleTime: ACTIVE_TIMER_REVALIDATE_MS,
  gcTime: ACTIVE_TIMER_REVALIDATE_MS,
  refetchInterval: ACTIVE_TIMER_REVALIDATE_MS,
  queryFn: () => fetchActiveTimesheetTimer(staffMemberId)
});
async function refreshActiveTimesheetTimer(queryClient, staffMemberId) {
  return queryClient.fetchQuery({
    ...activeTimesheetTimerQueryOptions(staffMemberId),
    staleTime: 0
  });
}
function useActiveTimesheetTimer(options = {}) {
  const queryClient = useQueryClient();
  const query = useQuery(activeTimesheetTimerQueryOptions(options.staffMemberId));
  const data = query.data ?? EMPTY_ACTIVE_TIMER;
  const refresh = React.useCallback(
    () => refreshActiveTimesheetTimer(queryClient, options.staffMemberId),
    [queryClient, options.staffMemberId]
  );
  return {
    ...data,
    isLoading: query.isLoading,
    isFetching: query.isFetching,
    error: query.error instanceof Error ? query.error : null,
    refresh
  };
}
export {
  activeTimesheetTimerQueryKey,
  activeTimesheetTimerQueryOptions,
  refreshActiveTimesheetTimer,
  useActiveTimesheetTimer
};
//# sourceMappingURL=useActiveTimesheetTimer.js.map
