import type { RouteParams } from "@/core/types/common";
import type { Metadata, ResolvingMetadata, ServerRuntime } from "next";
import type { JSX } from "react";

import { isShopAdmin } from "@/app/(visualization)/project/_actions";
import Logger from "@/core/utils/helpers/logger";
import dynamic from "next/dynamic";

import RedirectProvider from "@/core/common/RedirectProvider";

const DynamicUnityComponent = dynamic(
  () => import("@/core/common/Unity")
);

type Params = { modelId: string };

export const runtime: ServerRuntime = "nodejs";

export async function generateMetadata(props: RouteParams<Params>,
                                       parent: ResolvingMetadata): Promise<Metadata> {
  const id = (await props.params).modelId;
  console.log("Generating Metadata...");
  return {
    metadataBase: new URL("http://vps3.happyuser:3000"),
    title: `3D Model | ${id} | Rendersee`,
    description: `Interactive 3D building model viewer.\nCustomization of the interior.\nThe project with ID: ${id}`,
  }
}

export default async function ModelViewer({ params }: RouteParams<Params>): Promise<JSX.Element> {
  const { modelId } = await params;

  const showroom = await isShopAdmin();
  const testProject = modelId === "678f9970cd53c0aab651d640";

  try {
    return (
      (<RedirectProvider sourceKey={"customization_source"}>
        <DynamicUnityComponent id={modelId}
                               showroom={showroom}
                               testProject={testProject} />
      </RedirectProvider>)
    );
  } catch (error: any) {
    Logger.log("Error loading 3D model's page: ", error);
    throw new Error("Unity build not found: ", error);
  }
}
