import { jsxs as s, jsx as t } from "react/jsx-runtime";
import { useState as r, useEffect as z, useMemo as Ke } from "react";
import { Box as g, Card as Pe, Typography as x, Accordion as se, AccordionSummary as re, AccordionDetails as le, TextField as je, Button as b } from "@mui/material";
import O from "@/common/services/util/GeneralUtil";
import { api as $ } from "@/common/interceptors/AxiosInterceptor";
import { execute as $e, downloadExcel as Ue } from "@/common/services/GlobalApis";
import { getAssignedFeatures as Je } from "@/utils/feature.js";
import { useSelector as j } from "react-redux";
import ie from "@/views/custom-components/CustomTextField";
import { useForm as We } from "react-hook-form";
import Ye from "@/hooks/useTrackEvent";
import Ge from "@/views/custom-components/CustomConfirmationModal";
import { showToast as i } from "@/common/toaster/toaster";
import { Link as ce } from "react-router-dom";
import Ve from "dayjs";
import { useTranslateProvider as Xe } from "@/common/languageTranslator/TranslationContext";
import de from "prop-types";
import { getUseSkeleton as fe } from "@/store/reducers/SkeletonReducer";
import { Grid as K } from "@mui/system";
import Ze from "@/views/custom-components/CustomTextArea";
import P from "@/views/custom-components/CustomizedTable/CustomizedTableV2";
import { faChevronDown as me } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon as ue } from "@fortawesome/react-fontawesome";
import et from "lodash/debounce";
import './QueryManagement.css';const tt = (d) => $.post("resource/getdatawithtimeout", d), at = (d) => $.post("querymanagement/retrieve", d, {
  headers: { "Content-Type": "application/json" },
  transformRequest: [(o) => o]
}), nt = (d) => $.post("querymanagement/execute", d, {
  headers: { "Content-Type": "application/json" },
  transformRequest: [(o) => o]
}), he = ({ children: d, loading: o }) => !j(fe) || !o ? d : /* @__PURE__ */ s("div", { className: "flex flex-col space-y-4 h-[100vh] pt-3 relative w-full", children: [
  /* @__PURE__ */ s("div", { className: " flex flex-row space-x-2 overflow-auto", children: [
    /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[100%] h-[50px] " }),
    /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[100%] h-[50px] mx-[10px]" })
  ] }),
  /* @__PURE__ */ s("div", { className: " flex flex-col flex-1 ", children: [
    /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse h-[10rem] w-full  rounded-md mb-2" }),
    /* @__PURE__ */ s("div", { className: "flex  h-40  space-x-6", children: [
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-60 h-[40px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[130px] h-[40px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[130px] h-[40px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[130px] h-[40px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[130px] h-[40px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-[130px] h-[40px]" })
    ] })
  ] })
] });
he.propTypes = {
  children: de.any,
  loading: de.any
};
const pe = { pagination: !1 }, ye = { tableStyle: { maxHeight: 180 } }, ot = {
  pagination: !1,
  paginationType: "virtual-scroll"
}, st = { tableStyle: { maxHeight: "60vh" } }, Lt = () => {
  const d = j(fe), [o, U] = r({}), A = async (e, a = null) => {
    let n;
    return a === "index" ? n = "SELECT * FROM pg_indexes WHERE tablename = '" + e.tablename + "' limit 100" : a === "ddl" ? n = `WITH table_columns AS (
          SELECT 
              c.relname AS table_name, 
              a.attname AS column_name,
              pg_catalog.format_type(a.atttypid, a.atttypmod) AS column_type,
              CASE 
                  WHEN a.attnotnull THEN 'not null' 
                  ELSE 'null' 
              END AS column_constraint
          FROM 
              pg_class c
              JOIN pg_attribute a ON a.attrelid = c.oid
              JOIN pg_type t ON a.atttypid = t.oid
          WHERE 
              c.relname = '${e.tablename}'
              AND a.attnum > 0 -- Exclude system columns
          ORDER BY a.attnum
      ),
      table_indexes AS (
          SELECT 
              t.relname AS table_name,
              i.relname AS index_name,
              pg_catalog.pg_get_indexdef(ix.indexrelid) AS index_def
          FROM 
              pg_class t
              JOIN pg_index ix ON t.oid = ix.indrelid
              JOIN pg_class i ON i.oid = ix.indexrelid
          WHERE 
              t.relname = '${e.tablename}'
      )
      SELECT 
          'CREATE TABLE ' || tc.table_name || E'
(
' ||
          array_to_string(
              array_agg(
                  DISTINCT '    ' || tc.column_name || ' ' || tc.column_type || ' ' || tc.column_constraint
              ),
              E',
'
          ) || E'
);
' ||
          COALESCE(
              string_agg(
                  DISTINCT ti.index_def,
                  E'
'
              ), 
              ''
          ) AS ddl
      FROM 
          table_columns tc
      LEFT JOIN table_indexes ti ON tc.table_name = ti.table_name
      GROUP BY 
          tc.table_name;
      ` : n = `select * from ${e.tablename} limit 100`, w(n), f(n), {};
  }, ge = async (e) => {
    w(e.query), k(0);
  }, [J, xe] = r(null), [p, w] = r(""), [v, S] = r(0), be = [
    { field: "Sr. No.", label: "#", align: "left" },
    { field: "size_pretty", label: "Size", align: "left" },
    {
      field: "tablename",
      label: "Table Name",
      align: "left",
      onClick: A
    },
    {
      field: "Action",
      label: "Action",
      align: "left",
      render: (e) => /* @__PURE__ */ t(
        b,
        {
          variant: "contained",
          color: "primary",
          size: "small",
          className: "text-[0.75rem]",
          onClick: () => A(e, "index"),
          children: l("Index")
        }
      )
    },
    {
      field: "DDL",
      label: "DDL",
      align: "left",
      render: (e) => /* @__PURE__ */ t(
        b,
        {
          variant: "contained",
          color: "primary",
          size: "small",
          className: "text-[0.75rem]",
          onClick: () => A(e, "ddl"),
          children: l("DDL")
        }
      )
    }
  ], we = [
    { field: "Sr. No.", label: "#", align: "left" },
    {
      field: "query",
      label: "Query",
      align: "left",
      onClick: ge
    },
    { field: "created_on", label: "Executed On", align: "left" }
  ], [ve, Ne] = r([]), [I, D] = r([]), [_e, Ce] = r(!1), { user: Q } = j((e) => e.Authenticate), [T, Se] = r([]), [Te, W] = r([]), [Y, Ee] = r([]), [De, ke] = r([]), G = I.length || null, N = "select pid,query,wait_event_type,state_change,cast (now()-state_change as TEXT) as Since from pg_stat_activity where state = 'active' order by state_change", V = `select pg_terminate_backend( ${J} )`, R = "select cast(pid as text) as pid, cast(usename as text) as usename, cast(pg_blocking_pids(pid) as text) as blocked_by, datname as Database_Name,cast(query as text) as blocked_query from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0", { translate: l } = Xe(), [X, F] = r(!1), [Z, k] = r(0), [Le, u] = r(!1), [qe, H] = r(!1), [ee, L] = r(!0), {
    control: M,
    setValue: te,
    getValues: E,
    formState: { errors: Oe }
  } = We({
    mode: "onChange",
    defaultValues: {
      excelFileName: ""
    }
  });
  z(() => {
    W(T);
  }, [T]), z(() => {
    if (p) {
      if ((p == null ? void 0 : p.length) > 0) {
        L(!1), te("query", p);
        return;
      }
      L(!0);
    }
  }, [p]);
  const ae = Ye(), f = async (e, a = []) => {
    try {
      if (!e) {
        i({ message: "Query can not be empty", type: "error" });
        return;
      }
      u(!0);
      const { data: n } = await at(e).catch((m) => {
        D([]), console.error(m), u(!1), i({ message: `${m.response.data.message}`, type: "error" });
      });
      if (n && !n.length) {
        k(0), D([]), i({ message: "No data found", type: "info" }), u(!1);
        return;
      }
      if (n != null && n.length && (k(0), e !== N && i({
        message: "Query Executed Successfully",
        type: "success"
      })), e === N)
        a = [
          {
            label: "KILL PROCESS",
            icon: /* @__PURE__ */ t(
              b,
              {
                variant: "contained",
                color: "error",
                className: "text-[0.75rem]",
                children: l("Kill Process")
              }
            ),
            onClick: Qe
          }
        ];
      else if (e === V) {
        n != null && n.length && i({ message: "Terminated Successfully", type: "success" }), D([]);
        return;
      }
      D(
        n.map((m, _) => ({ index: _ + 1, ...m }))
      );
      const c = Object.keys(n[0]);
      (a.length || e === N) && c.push("Actions");
      const y = c.map((m) => ({
        field: m,
        label: m,
        align: "left"
      }));
      ke(a), Ne([
        { field: "index", label: "#", align: "left" },
        ...y
      ]), q(), u(!1);
    } catch (n) {
      u(!1), console.error(n);
    }
  }, ne = async (e) => {
    try {
      if (!e) {
        i({ message: "Query can not be empty", type: "error" });
        return;
      }
      const { data: a } = await nt(e).catch((n) => {
        console.error(n), i({ message: `${n.response.data.message}`, type: "error" });
      });
      a.length || i({ message: "No data found", type: "info" }), a.length && i({ message: "Query updated successfully", type: "success" });
    } catch (a) {
      console.error(a);
    }
  }, Ae = async () => {
    const e = "d91d249f-c8e1-4397-a84d-6ce6eb33eb48", a = E("query"), n = E("excelFileName");
    if (!a) {
      i({ message: "Query can not be empty", type: "info" });
      return;
    }
    try {
      u(!0);
      const y = await Ue(e, {
        paramObj: { query: a }
      }).catch(
        (h) => (console.error(h), i({
          message: "Operation Unsuccessful, Something went wrong",
          type: "error"
        }), null)
      );
      if (!y) {
        u(!1);
        return;
      }
      const m = new Blob([y.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      }), _ = `${n || "rename"}_${(/* @__PURE__ */ new Date()).getTime()}.xlsx`;
      if (navigator.msSaveBlob) {
        const h = new Blob([y.data], { type: "" }), B = (h.size / 1024).toFixed(2);
        return ae("file_download", {
          file_type: "xlsx",
          file_name: _,
          file_size: `${B} KB`,
          download_status: "success"
        }), navigator.msSaveBlob(h, _);
      } else {
        const h = URL.createObjectURL(m), B = (m.size / 1024).toFixed(2), C = document.createElement("a");
        C.href = h, C.download = _, C.style.display = "none", document.body.appendChild(C), C.click(), ae("file_download", {
          file_type: "xlsx",
          file_name: _,
          file_size: `${B} KB`,
          download_status: "success"
        }), URL.revokeObjectURL(h), C.remove();
      }
      u(!1);
    } catch (c) {
      console.error(c), u(!1), i({ type: "error", message: "Something went wrong!" });
    }
  }, Ie = async () => {
    try {
      Ce(!0), w(R), await f(R);
    } catch (e) {
      console.error(e);
    }
  }, Qe = async (e) => {
    S(3), xe(e.pid);
  }, Re = async () => {
    try {
      await f(V);
      let e;
      _e === !0 ? e = R : e = N, await f(e);
    } catch (e) {
      console.error(e);
    }
  }, Fe = async () => {
    try {
      w(N), await f(N);
    } catch (e) {
      console.error(e);
    }
  }, q = async () => {
    try {
      const e = E("queryHistorySearchKey"), { data: a } = await $e({
        code: "retrieve_limited_query_history",
        parameters: {
          userId: Q == null ? void 0 : Q.id,
          limit: 100,
          searchKey: e
        }
      });
      Ee(
        a.result.map((n, c) => ({
          index: c + 1,
          ...n,
          created_on: Ve(n.created_on).format("DD-MM-YYYY h:mm:ss A")
        }))
      );
    } catch (e) {
      console.error(e);
    }
  }, He = async () => {
    try {
      F((a) => !a);
      const { data: e } = await Je("techo.querymanagement");
      e && U(JSON.parse(e)), q(), F((a) => !a);
    } catch {
      F(!1);
    }
  };
  z(() => {
    He();
  }, []);
  const Me = async () => {
    try {
      H(!0);
      const { data: e } = await tt({
        code: "retrieve_all_tables"
      });
      Se(
        e.result.map((a, n) => ({
          index: n + 1,
          ...a
        }))
      ), H(!1);
    } catch (e) {
      console.error(e), H(!1);
    }
  }, Be = (e) => {
    const a = e.target.value;
    ze(a);
  }, ze = Ke(
    () => et((e) => {
      const a = e.toLowerCase(), n = T.filter(
        (c) => {
          var y;
          return (y = c == null ? void 0 : c.tablename) == null ? void 0 : y.toLowerCase().includes(a);
        }
      );
      W(n);
    }, 300),
    // debounce time in ms
    [T]
  ), oe = (e, a) => {
    k(a ? e : !1);
  };
  return O.isTecho && !X && !(o != null && o["view.manage.querymanagement.retrieve"]) ? /* @__PURE__ */ t(g, { className: "flex justify-center items-center w-full h-[80vh]", children: /* @__PURE__ */ t(
    Pe,
    {
      className: "h-80 w-150 flex justify-center items-center",
      children: /* @__PURE__ */ t(x, { variant: "h5", className: "text-customBlue", children: "You dont have permission to view Query Management" })
    }
  ) }) : /* @__PURE__ */ s(he, { loading: X, children: [
    Le && d && /* @__PURE__ */ t("div", { className: "loader-overlay", children: /* @__PURE__ */ t("div", { className: "loader-spinner" }) }),
    /* @__PURE__ */ s(g, { minHeight: "80vh", className: "flex flex-col mt-5", children: [
      /* @__PURE__ */ s(
        g,
        {
          className: "flex flex-col md:flex-row md:space-x-2 space-y-2 md:space-y-0",
          children: [
            /* @__PURE__ */ t(K, { className: "w-full md:w-1/2", children: /* @__PURE__ */ s(
              se,
              {
                expanded: Z === 1,
                onChange: (e, a) => {
                  a && !T.length && Me(), oe(1, a);
                },
                "data-testid": "table-list-accordion",
                className: "accordion",
                children: [
                  /* @__PURE__ */ t(
                    re,
                    {
                      expandIcon: /* @__PURE__ */ t(ue, { icon: me }),
                      "data-testid": "table-list-accordion-title",
                      sx: {
                        "&.Mui-expanded": {
                          minHeight: "unset",
                          paddingBottom: "2px",
                          "& .MuiAccordionSummary-content": {
                            marginBottom: "2px"
                          }
                        }
                      },
                      children: /* @__PURE__ */ t(x, { children: l("All Table List") })
                    }
                  ),
                  /* @__PURE__ */ s(
                    le,
                    {
                      className: "accordion-details mt-2.5",
                      sx: {
                        backgroundColor: "background.paper",
                        ".Mui-expanded &": {
                          opacity: 1,
                          pointerEvents: "auto"
                        }
                      },
                      children: [
                        /* @__PURE__ */ t(
                          je,
                          {
                            id: "tableListSearchKey",
                            onChange: Be,
                            size: "small",
                            placeholder: "Search Table Name",
                            className: "w-[70%] mb-2"
                          }
                        ),
                        /* @__PURE__ */ t(
                          P,
                          {
                            strip: !0,
                            isLoading: qe,
                            columns: be,
                            tableData: Te,
                            paginationConfig: pe,
                            dataTestId: "table-list-table-customized",
                            styleConfig: ye
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ t(K, { className: "w-full md:w-1/2", children: /* @__PURE__ */ s(
              se,
              {
                expanded: Z === 2,
                onChange: (e, a) => {
                  a && !Y.length && q(), oe(2, a);
                },
                "data-testid": "query-history-accordion",
                className: "accordion",
                children: [
                  /* @__PURE__ */ t(
                    re,
                    {
                      expandIcon: /* @__PURE__ */ t(ue, { icon: me }),
                      "data-testid": "query-history-accordion-title",
                      sx: {
                        "&.Mui-expanded": {
                          minHeight: "unset",
                          paddingBottom: "2px",
                          "& .MuiAccordionSummary-content": {
                            marginBottom: "2px"
                          }
                        }
                      },
                      children: /* @__PURE__ */ t(x, { children: l("Query History") })
                    }
                  ),
                  /* @__PURE__ */ s(
                    le,
                    {
                      className: "accordion-details mt-2.5",
                      sx: {
                        backgroundColor: "background.paper",
                        ".Mui-expanded &": {
                          opacity: 1,
                          pointerEvents: "auto"
                        }
                      },
                      test: "work",
                      children: [
                        /* @__PURE__ */ s(g, { className: "flex items-center mb-2", children: [
                          /* @__PURE__ */ t(
                            ie,
                            {
                              id: "queryHistorySearchKey",
                              name: "queryHistorySearchKey",
                              control: M,
                              placeholder: "Search in History",
                              size: "small",
                              className: "w-auto mr-1"
                            }
                          ),
                          /* @__PURE__ */ t(
                            b,
                            {
                              variant: "contained",
                              color: "primary",
                              onClick: q,
                              "data-testid": "query-history-accordion-submit",
                              sx: { ml: { xs: "10px", md: "0px" } },
                              children: l("Search")
                            }
                          )
                        ] }),
                        /* @__PURE__ */ t(
                          P,
                          {
                            strip: !0,
                            columns: we,
                            tableData: Y,
                            paginationConfig: pe,
                            dataTestId: "query-history-table-customized",
                            styleConfig: ye
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ) })
          ]
        }
      ),
      /* @__PURE__ */ s(g, { className: "flex flex-col space-y-4", children: [
        /* @__PURE__ */ t(
          Ze,
          {
            control: M,
            minRows: 5,
            variant: "outlined",
            placeholder: "Type your query here...",
            id: "query",
            name: "query",
            className: "mt-5",
            sx: { backgroundColor: "background.paper" },
            errors: Oe,
            margin: "normal",
            dataTestId: "query-text-area",
            onChange: (e) => {
              var a, n;
              if (te("query", e.target.value), ((n = (a = e == null ? void 0 : e.target) == null ? void 0 : a.value) == null ? void 0 : n.length) > 0) {
                L(!1);
                return;
              }
              L(!0);
            }
          }
        ),
        /* @__PURE__ */ s(g, { className: "flex flex-col md:flex-row md:items-center mb-4 gap-3", children: [
          /* @__PURE__ */ t(
            ie,
            {
              id: "excelFileName",
              name: "excelFileName",
              className: "m-0 p-0",
              control: M,
              placeholder: "Enter File Name",
              size: "small",
              fullWidth: !1,
              dataTestId: "enter-file-field"
            }
          ),
          (!O.isTecho || (o == null ? void 0 : o["view.manage.querymanagement.downloadExcel"])) && /* @__PURE__ */ t(
            b,
            {
              variant: "contained",
              color: "info",
              onClick: Ae,
              "data-testid": "download-excel-button",
              children: l("Download Excel")
            }
          ),
          /* @__PURE__ */ s(g, { className: "m-1 flex", children: [
            /* @__PURE__ */ t(ce, { onClick: () => Ie(), className: "m-1", children: /* @__PURE__ */ t(x, { variant: "body2", color: "info", children: l("Fetch Locked Queries") }) }),
            /* @__PURE__ */ t(x, { variant: "body2", className: "m-1", children: "|" }),
            /* @__PURE__ */ t(ce, { onClick: Fe, className: "m-1", children: /* @__PURE__ */ t(x, { variant: "body2", color: "info", children: l("Populate State Query") }) })
          ] }),
          (!O.isTecho || (o == null ? void 0 : o["view.manage.querymanagement.retrieve"])) && /* @__PURE__ */ t(
            b,
            {
              variant: "contained",
              color: "success",
              onClick: async () => {
                const e = E("query");
                if (w(e), e != null && e.toLowerCase().includes("where")) {
                  await f(e);
                  return;
                }
                S(1);
              },
              "data-testid": "retrieve-data-button",
              disabled: ee,
              children: l("Retrieve Data")
            }
          ),
          (!O.isTecho || (o == null ? void 0 : o["view.manage.querymanagement.execute"])) && /* @__PURE__ */ t(
            b,
            {
              variant: "contained",
              color: "secondary",
              onClick: async () => {
                const e = E("query");
                if (w(e), e != null && e.toLowerCase().includes("where")) {
                  await ne(e);
                  return;
                }
                S(2);
              },
              "data-testid": "execute-button",
              disabled: ee,
              children: l("Execute")
            }
          )
        ] }),
        !!G && /* @__PURE__ */ s(x, { variant: "body2", children: [
          l("Total rows fetched"),
          " :",
          " ",
          /* @__PURE__ */ s("strong", { children: [
            " ",
            G
          ] }),
          " "
        ] }),
        !!I.length && /* @__PURE__ */ t(K, { className: "max-h-[80vh] overflow-x-auto mb-2", children: /* @__PURE__ */ t(
          P,
          {
            className: "min-w-[500px]",
            columns: ve,
            actions: De,
            tableData: I,
            paginationConfig: ot,
            dataTestId: "query-output-table-customized",
            styleConfig: st
          }
        ) }),
        !!v && /* @__PURE__ */ t(
          Ge,
          {
            description: v === 3 ? `Are you sure you want to kill process id ${J}` : "The query does not include where clause. Are you sure you want to proceed ?",
            title: "CONFIRM ACTION",
            open: v,
            handleClick: async () => {
              v === 1 && f(p), v === 2 && ne(p), v === 3 && Re(), S(0);
            },
            handleClose: () => S(0),
            dataTestId: "modal"
          }
        )
      ] })
    ] })
  ] });
};
export {
  Lt as default
};
//# sourceMappingURL=QueryManagement-BpIRH8hI.js.map
