"use client";

import { useCallback } from "react";
import { useI18n } from "@/lib/i18n/context";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { useDashboardShell } from "@/components/dashboard/DashboardShellContext";
import { saveFailureMessage, saveServerReceipts, SaveReceiptsResult } from "@/lib/storage/server";

/**
 * Persists receipts to PostgreSQL and surfaces failures as a dashboard toast
 * instead of swallowing `false`.
 */
export function usePersistReceipts(userId: string) {
  const { pushToast } = useDashboardShell();
  const { language } = useI18n();
  const isDe = language === "de";

  return useCallback(
    async (receipts: ProcessedReceipt[]): Promise<SaveReceiptsResult> => {
      const result = await saveServerReceipts(receipts, userId);
      if (!result.ok) {
        pushToast({
          tone: "error",
          title: isDe ? "Speichern fehlgeschlagen" : "Save failed",
          message: saveFailureMessage(result, isDe),
          durationMs: 10000,
        });
      }
      return result;
    },
    [userId, pushToast, isDe]
  );
}
