import { defineComponent as pe, useId as fe, ref as j, inject as Q, computed as m, watch as Y, onMounted as ye, createBlock as w, createCommentVNode as J, unref as r, openBlock as g, withCtx as s, createVNode as n, createElementVNode as U, renderSlot as $, createTextVNode as b, createElementBlock as D, Fragment as Z, toDisplayString as H } from "vue";
import { useWorkspace as ve } from "@scalar/api-client/store";
import { getHarRequest as ge, getSnippet as xe } from "@scalar/api-client/views/Components/CodeSnippet";
import { filterSecurityRequirements as he } from "@scalar/api-client/views/Request/RequestSection";
import { ScalarCodeBlock as qe } from "@scalar/components";
import { freezeElement as Ee } from "@scalar/helpers/dom/freeze-element";
import { requestSchema as Ke, createExampleFromRequest as be } from "@scalar/oas-utils/entities/spec";
import { isDereferenced as Se } from "@scalar/openapi-types/helpers";
import I from "../../components/ScreenReader.vue.js";
import { useConfig as ke } from "../../hooks/useConfig.js";
import { EXAMPLE_CONTEXT as Ce, DISCRIMINATOR_CONTEXT as Oe } from "../../hooks/useDiscriminator.js";
import { useHttpClientStore as Ne } from "../../stores/useHttpClientStore.js";
import $e from "./ExamplePicker.vue.js";
import Te from "./TextSelect.vue.js";
/* empty css                */
import _ from "../../components/Card/Card.vue.js";
import Ve from "../../components/Card/CardHeader.vue.js";
import ee from "../../components/HttpMethod/HttpMethod.vue.js";
import te from "../../components/Card/CardContent.vue.js";
import Re from "../../components/Card/CardFooter.vue.js";
import { useExampleStore as Be } from "../../legacy/stores/useExampleStore.js";
const je = ["id"], we = ["id"], Je = {
  key: 0,
  class: "request-card-footer-addon"
}, Ue = { class: "request-header" }, ot = /* @__PURE__ */ pe({
  __name: "ExampleRequest",
  props: {
    server: {},
    collection: {},
    operation: {},
    request: {},
    method: {},
    fallback: { type: Boolean },
    schemas: {}
  },
  setup(l) {
    const { selectedExampleKey: M, operationId: ae } = Be(), { requestExamples: S, securitySchemes: A, requestExampleMutators: T } = ve(), le = ke(), {
      httpClient: u,
      setHttpClient: re,
      availableTargets: F,
      httpTargetTitle: oe,
      httpClientTitle: se
    } = Ne(), k = fe(), x = j(!1), C = Q(Ce), f = Q(Oe), V = m(() => {
      var e;
      return (e = f == null ? void 0 : f.value) == null ? void 0 : e.selectedType;
    }), P = m(
      () => {
        var e;
        return ((e = f == null ? void 0 : f.value) == null ? void 0 : e.hasDiscriminator) || !1;
      }
    ), d = m(() => {
      var t;
      const e = ["x-custom-examples", "x-codeSamples", "x-code-samples"];
      for (const a of e)
        if ((t = l.operation) != null && t[a])
          return [...l.operation[a]];
      return [];
    }), o = j(
      // Default to first custom example
      d.value.length ? {
        targetKey: "customExamples",
        clientKey: 0
      } : (
        // Otherwise use the globally selected HTTP client
        {
          targetKey: u.targetKey,
          clientKey: u.clientKey
        }
      )
    );
    Y(u, () => {
      o.value = {
        targetKey: u.targetKey,
        clientKey: u.clientKey
      };
    });
    const X = m(() => {
      const e = O.value;
      return Object.keys(e).length > 1;
    }), ne = () => {
      var q, E, c;
      if (o.value.targetKey === "customExamples")
        return ((q = d.value[o.value.clientKey]) == null ? void 0 : q.source) ?? "";
      const e = u.clientKey, t = u.targetKey, a = l.request || Ke.parse({
        uid: l.operation.operationId || "temp-request",
        method: l.method,
        path: l.operation.path,
        parameters: l.operation.parameters || [],
        requestBody: l.operation.requestBody,
        examples: [],
        type: "request",
        selectedSecuritySchemeUids: [],
        selectedServerUid: "",
        servers: [],
        summary: l.operation.summary || "Example Request"
      });
      let i = S[((c = (E = l.request) == null ? void 0 : E.examples) == null ? void 0 : c[0]) ?? ""];
      if (!i) {
        const B = O.value, K = Object.keys(B)[0];
        i = be(a, K);
      }
      const p = he(
        l.operation.security || l.collection.security,
        l.collection.selectedSecuritySchemeUids,
        A
      ), y = ge({
        operation: a,
        example: i,
        server: l.server,
        securitySchemes: p
      }), [h, N] = xe(t, e, y);
      return h ? h.message ?? "" : N;
    }, z = m(() => {
      try {
        return ne();
      } catch (e) {
        return console.error("[generateSnippet]", e), "";
      }
    }), O = m(() => {
      var a;
      if (!Se(l.operation.requestBody))
        return {};
      const e = ((a = l.operation.requestBody) == null ? void 0 : a.content) ?? {}, t = Object.values(e)[0];
      return (t == null ? void 0 : t.examples) ?? {};
    }), ue = m(() => {
      var t, a;
      const e = (
        // Specified language
        ((t = o.value) == null ? void 0 : t.targetKey) === "customExamples" ? ((a = d.value[o.value.clientKey]) == null ? void 0 : a.lang) ?? "plaintext" : (
          // Or language for the globally selected HTTP client
          u.targetKey
        )
      );
      return e === "shell" && z.value.includes("curl") ? "curl" : e === "Objective-C" ? "objc" : e;
    }), ie = m(
      () => Object.values(A).flatMap((e) => e.type === "apiKey" ? e.value : (e == null ? void 0 : e.type) === "http" ? [
        e.token,
        e.password,
        btoa(`${e.username}:${e.password}`)
      ] : e.type === "oauth2" ? Object.values(e.flows).map((t) => t.token) : [])
    ), ce = m(() => {
      const e = F.value.map((t) => ({
        value: t.key,
        label: t.title,
        options: t.clients.map((a) => ({
          value: JSON.stringify({
            targetKey: t.key,
            clientKey: a.client
          }),
          label: a.title
        }))
      }));
      return d.value.length && e.unshift({
        value: "customExamples",
        label: "Examples",
        options: d.value.map((t, a) => ({
          value: JSON.stringify({
            targetKey: "customExamples",
            clientKey: a
          }),
          label: t.label ?? t.lang ?? `Example #${a + 1}`
        }))
      }), e;
    }), R = j(null);
    function me(e) {
      const t = JSON.parse(e);
      if (R.value) {
        const a = Ee(R.value.$el);
        setTimeout(() => {
          a();
        }, 300);
      }
      t.targetKey === "customExamples" || o.value.targetKey === "customExamples" && t.targetKey === u.targetKey && t.clientKey === u.clientKey ? o.value = t : re(t);
    }
    function de(e) {
      var i, p;
      M.value = e, ae.value = l.operation.operationId;
      const t = S[((p = (i = l.request) == null ? void 0 : i.examples) == null ? void 0 : p[0]) ?? ""], a = O.value[e];
      if (t && (a != null && a.value))
        try {
          T.edit(
            t.uid,
            "body.raw.value",
            JSON.stringify(a.value, null, 2)
          );
        } catch (y) {
          console.error("[handleExampleUpdate]", y);
        }
    }
    ye(() => {
      P.value && V.value && !x.value && L(V.value);
    });
    const L = (e) => {
      var t, a, i, p, y, h, N, q, E;
      if (!x.value)
        try {
          x.value = !0;
          const c = S[l.operation.examples[0]];
          if (c && (C != null && C.generateExampleValue)) {
            const B = (a = (t = c.body) == null ? void 0 : t.raw) != null && a.value ? JSON.parse(c.body.raw.value) : void 0, K = C.generateExampleValue(
              Array.isArray(B)
            );
            if (T.edit(
              c.uid,
              "body.raw.value",
              JSON.stringify(K, null, 2)
            ), (p = (i = l.request) == null ? void 0 : i.examples) != null && p[0]) {
              const v = S[(h = (y = l.request) == null ? void 0 : y.examples) == null ? void 0 : h[0]];
              v && T.edit(
                v.uid,
                "body.raw.value",
                JSON.stringify(K, null, 2)
              );
            }
            if ((E = (q = (N = l.operation.requestBody) == null ? void 0 : N.content) == null ? void 0 : q["application/json"]) != null && E.examples) {
              const v = l.operation.requestBody.content["application/json"].examples;
              Object.keys(v).forEach((W) => {
                var G;
                (G = v[W]) != null && G.value && (v[W].value = K);
              });
            }
          }
        } catch (c) {
          console.error("[handleDiscriminatorChange]", c);
        } finally {
          x.value = !1;
        }
    };
    return Y(V, (e) => {
      e && P.value && !x.value && L();
    }), (e, t) => r(F).length || d.value.length ? (g(), w(r(_), {
      key: 0,
      "aria-labelledby": `${r(k)}-header`,
      class: "dark-mode",
      ref_key: "elem",
      ref: R,
      role: "region"
    }, {
      default: s(() => [
        n(r(Ve), { muted: "" }, {
          actions: s(() => [
            n(Te, {
              class: "request-client-picker",
              controls: `${r(k)}-example`,
              modelValue: JSON.stringify(o.value),
              options: ce.value,
              "onUpdate:modelValue": me
            }, {
              default: s(() => [
                o.value.targetKey === "customExamples" ? (g(), D(Z, { key: 0 }, [
                  n(I, null, {
                    default: s(() => t[1] || (t[1] = [
                      b("Selected Example:")
                    ])),
                    _: 1
                  }),
                  b(" " + H(d.value[o.value.clientKey].label ?? "Example"), 1)
                ], 64)) : (g(), D(Z, { key: 1 }, [
                  n(I, null, {
                    default: s(() => t[2] || (t[2] = [
                      b("Selected HTTP client:")
                    ])),
                    _: 1
                  }),
                  b(" " + H(r(oe)) + " " + H(r(se)), 1)
                ], 64))
              ]),
              _: 1
            }, 8, ["controls", "modelValue", "options"])
          ]),
          default: s(() => [
            U("div", {
              id: `${r(k)}-header`,
              class: "request-header"
            }, [
              n(I, null, {
                default: s(() => t[0] || (t[0] = [
                  b("Request Example for")
                ])),
                _: 1
              }),
              n(r(ee), {
                as: "span",
                class: "request-method",
                method: e.method
              }, null, 8, ["method"]),
              $(e.$slots, "header", {}, void 0, !0)
            ], 8, je)
          ]),
          _: 3
        }),
        n(r(te), {
          borderless: "",
          class: "request-editor-section custom-scroll",
          frameless: ""
        }, {
          default: s(() => [
            U("div", {
              id: `${r(k)}-example`,
              class: "code-snippet"
            }, [
              n(r(qe), {
                class: "bg-b-2 -outline-offset-2",
                content: z.value,
                hideCredentials: ie.value,
                lang: ue.value,
                lineNumbers: ""
              }, null, 8, ["content", "hideCredentials", "lang"])
            ], 8, we)
          ]),
          _: 1
        }),
        (X.value || !r(le).hideTestRequestButton) && e.$slots.footer ? (g(), w(r(Re), {
          key: 0,
          class: "request-card-footer",
          contrast: ""
        }, {
          default: s(() => [
            X.value ? (g(), D("div", Je, [
              n($e, {
                class: "request-example-selector",
                examples: O.value,
                modelValue: r(M),
                "onUpdate:modelValue": de
              }, null, 8, ["examples", "modelValue"])
            ])) : J("", !0),
            $(e.$slots, "footer", {}, void 0, !0)
          ]),
          _: 3
        })) : J("", !0)
      ]),
      _: 3
    }, 8, ["aria-labelledby"])) : e.fallback ? (g(), w(r(_), {
      key: 1,
      class: "dark-mode"
    }, {
      default: s(() => [
        n(r(te), { class: "request-card-simple" }, {
          default: s(() => [
            U("div", Ue, [
              n(r(ee), {
                as: "span",
                class: "request-method",
                method: e.method
              }, null, 8, ["method"]),
              $(e.$slots, "header", {}, void 0, !0)
            ]),
            $(e.$slots, "footer", {}, void 0, !0)
          ]),
          _: 3
        })
      ]),
      _: 3
    })) : J("", !0);
  }
});
export {
  ot as default
};
