/* eslint-disable no-underscore-dangle */
import { Client } from "@opensearch-project/opensearch";
import { VisualizationDetail } from "app/_components/VisualizationDetail";

const getVisualization = async (visualizationID: string) => {
  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: any) => hit._id.split(":")[1] === visualizationID[0]
  );
  const hit = hits[0];
  const 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 visualization;
};

type PageProps = {
  params: {
    visualizationID: string;
  };
};

export default async function Page({ params: { visualizationID } }: PageProps) {
  const visualization = await getVisualization(visualizationID);

  return <VisualizationDetail {...visualization} editing={false} />;
}
