import { getPropertyMeta } from "@/app/portfolio/[slug]/building-passport/[propertyId]/utils";
import { eq } from "drizzle-orm";
import { db } from "@/app/db/db";
import { uploadedFiles } from "@/app/db/schema/uploaded_files";
import { DocumentsClient, type RawFileType } from "./DocumentsClient";

export default async function DocumentsPage(props: {
  params: Promise<{ slug: string; propertyId: string }>;
}) {
  const params = await props.params;
  const { propertyId } = params;

  if (!propertyId || propertyId === "0") {
    throw Error("Invalid propertyId");
  }

  const propertyMeta = await getPropertyMeta(propertyId);

  const rows = await db
    .select({
      id: uploadedFiles.id,
      s3FileKey: uploadedFiles.s3FileKey,
      s3FileBucket: uploadedFiles.s3FileBucket,
      s3UploadTimestamp: uploadedFiles.s3UploadTimestamp,
      fileType: uploadedFiles.fileType,
    })
    .from(uploadedFiles)
    .where(eq(uploadedFiles.uprn, BigInt(propertyMeta.uprn)));

  const documents = rows.map((row) => ({
    id: String(row.id),
    s3FileKey: row.s3FileKey,
    s3FileBucket: row.s3FileBucket,
    docType: (row.fileType ?? "unknown") as RawFileType,
    s3UploadTimestamp: row.s3UploadTimestamp.toISOString(),
  }));

  return (
    <div className="mt-6 px-1">
      <DocumentsClient documents={documents} />
    </div>
  );
}
