/* eslint-disable no-underscore-dangle */
import { GetServerSideProps, GetServerSidePropsContext } from "next";
import { Client } from "@opensearch-project/opensearch";
import Head from "next/head";
import { Layout } from "components/Layout";
import { VisualizationDetail } from "components/VisualizationDetail";
import { checkAuth } from "lib/checkAuth";

const Visualization = ({ visualization }) => (
  <Layout>
    <Head>
      <title>Digital Threat Dashboard – Leafcutter</title>
    </Head>
    <VisualizationDetail {...visualization} />
  </Layout>
);

export default Visualization;

export const getServerSideProps: GetServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  const res: any = await checkAuth(context);

  if (res.redirect) {
    return res;
  }

  const { visualizationID } = context.query;

  const node = `https://${process.env.OPENSEARCH_USERNAME}:${process.env.OPENSEARCH_PASSWORD}@${process.env.OPENSEARCH_URL}`;
  const client = new Client({
    node,
    ssl: {
      rejectUnauthorized: false,
    },
  });

  const rawResponse = await client.search({
    index: ".kibana_1",
    size: 200,
  });
  const response = rawResponse.body;

  const hits = response.hits.hits.filter(
    (hit) => hit._id.split(":")[1] === visualizationID[0]
  );
  const hit = hits[0];
  res.props.visualization = {
    id: hit._id.split(":")[1],
    title: hit._source.visualization.title,
    description: hit._source.visualization.description,
    url: `/app/visualize?security_tenant=global#/edit/${
      hit._id.split(":")[1]
    }?embed=true`,
  };

  return res;
};
