<script setup>
import { Effect } from "effect";
import { toast } from "vue-sonner";
import { cel as _rawCel } from "../../../../../utils/cel";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
import { dispatchTriggers, useEventChannel } from "../../../../../share/event-bus";
import ShwfedActionDefinition from "../../../components/definition.vue";
defineOptions({ name: "ShwfedHttpDownloadActionRuntime" });
const props = defineProps({
  buttonId: { type: String, required: true },
  config: { type: null, required: true }
});
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const channel = useEventChannel();
const TOAST_STYLES = /* @__PURE__ */ new Set(["success", "error", "warning", "info"]);
function saveFile(file) {
  const url = URL.createObjectURL(file);
  const a = document.createElement("a");
  a.href = url;
  a.download = file.name;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}
const effect = Effect.suspend(() => Effect.gen(function* () {
  const { template, messageExpression, resultExpression } = props.config;
  const requestBuilder = yield* $cel(template.request);
  if (!template.download) {
    const file = yield* requestBuilder.file();
    yield* Effect.sync(() => saveFile(file));
    return yield* dispatchTriggers(channel, props.config.onSuccess);
  }
  const json = yield* requestBuilder.json();
  const context = { json };
  const kind = resultExpression === void 0 ? "success" : yield* Effect.map($cel(resultExpression, context), (s) => TOAST_STYLES.has(s) ? s : "success");
  if (messageExpression !== void 0) {
    const message = yield* $cel(messageExpression, context);
    yield* Effect.sync(() => toast[kind](message));
  }
  if (kind === "success" || kind === "info") {
    const downloadBuilder = yield* $cel(template.download, context);
    const file = yield* downloadBuilder.file();
    yield* Effect.sync(() => saveFile(file));
  }
  const triggers = {
    success: props.config.onSuccess,
    warning: props.config.onWarning,
    error: props.config.onError,
    info: props.config.onInfo
  };
  return yield* dispatchTriggers(channel, triggers[kind]);
}));
</script>

<template>
  <ShwfedActionDefinition
    :action-id="buttonId"
    :effect="effect"
  />
</template>
