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