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