import type { QueryClient } from "@tanstack/react-query";

import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import type {
  RuleEngineListResult,
  RuleEngineRecord,
  RuleEngineResourceSlug,
} from "@/types/rule-engine";

export function invalidateBookings(qc: QueryClient): Promise<void> {
  return qc.invalidateQueries({ queryKey: QUERY_KEYS.BOOKINGS.ROOT });
}

export function invalidateBookingDetail(
  qc: QueryClient,
  id: string,
): Promise<void> {
  return Promise.all([
    qc.invalidateQueries({ queryKey: QUERY_KEYS.BOOKINGS.byId(id) }),
    invalidateBookings(qc),
  ]).then(() => undefined);
}

/** Update a single row in all cached list queries for a rule-engine resource. */
export function patchRuleEngineListRecord(
  qc: QueryClient,
  resource: RuleEngineResourceSlug | string,
  updated: RuleEngineRecord,
): void {
  const updatedId = String(updated.id);
  qc.setQueriesData<RuleEngineListResult<RuleEngineRecord>>(
    { queryKey: ["rule-engine", "list", resource] },
    (old) => {
      if (!old?.data?.length) return old;
      const index = old.data.findIndex((row) => String(row.id) === updatedId);
      if (index === -1) return old;
      const data = old.data.slice();
      data[index] = { ...data[index], ...updated };
      return { ...old, data };
    },
  );
}

/** Invalidate and refetch active rule-engine list queries for a resource. */
export async function invalidateRuleEngineList(
  qc: QueryClient,
  resource: RuleEngineResourceSlug | string,
): Promise<void> {
  const queryKey = ["rule-engine", "list", resource] as const;
  await qc.invalidateQueries({ queryKey });
  await qc.refetchQueries({ queryKey, type: "active" });
}

export function invalidateRuleEngineRoot(qc: QueryClient): Promise<void> {
  return qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.ROOT });
}
