import { DocumentView } from "@/components/documents/DocumentView";
import { DocumentLoader } from "@/context/document/DocumentLoader";
import type { DocumentId } from "@/lib/types";
import { RelationshipType } from "@/lib/types";
import { createFileRoute } from "@tanstack/react-router";
import * as z from "zod";

export const Route = createFileRoute(
  "/_app/_authenticated/document/$documentId/$",
)({
  component: RouteComponent,
});

const documentParams = z
  .templateLiteral([
    z.string(),
    z.optional(z.literal("/")),
    z.optional(z.string()),
  ])
  .pipe(
    z.transform((path: string) => {
      if (path === "") {
        return {
          relationshipType: null,
          childDoc: null,
        };
      }
      const [relationshipType, childDoc] = path.split("/");
      return {
        relationshipType: (relationshipType ?? null) as RelationshipType | null,
        childDoc: (childDoc ?? null) as DocumentId | null,
      };
    }),
  );

function RouteComponent() {
  const { documentId, _splat } = Route.useParams();

  const { relationshipType, childDoc } = documentParams.parse(_splat);

  return (
    <DocumentLoader documentId={documentId as DocumentId}>
      <DocumentView
        documentId={documentId as DocumentId}
        relationshipType={relationshipType}
      />
    </DocumentLoader>
  );
}
