import type { HttpResponse } from "@yaakapp-internal/models";
import { getModel } from "@yaakapp-internal/models";
import mime from "mime";
import slugify from "slugify";
import { InlineCode } from "@yaakapp-internal/ui";
import { getContentTypeFromHeaders } from "../lib/model_util";
import { rpc } from "../lib/rpc";
import { showToast } from "../lib/toast";
import { useFastMutation } from "./useFastMutation";
import { platform } from "@yaakapp-internal/platform";

export function useSaveResponse(response: HttpResponse | null) {
  return useFastMutation({
    mutationKey: ["save_response", response?.id],
    mutationFn: async () => {
      if (response == null) return null;

      const request = getModel("http_request", response.requestId);
      if (request == null) return null;

      const contentType = getContentTypeFromHeaders(response.headers) ?? "unknown";
      const ext = mime.getExtension(contentType);
      const slug = slugify(request.name || "response", { lower: true });
      const filepath = await platform.dialog.save({
        defaultPath: ext ? `${slug}.${ext}` : slug,
        title: "Save Response",
      });
      if (filepath == null) {
        return; // Cancelled
      }

      await rpc("cmd_save_response", { responseId: response.id, filepath });
      showToast({
        message: (
          <>
            Response saved to <InlineCode>{filepath}</InlineCode>
          </>
        ),
      });
    },
  });
}
