import { auth } from "@/auth";
import { redirect, notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { Container } from "@mui/material";
import UpdateView from "./update-view";

export default async function UpdatePage({ params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  
  // Security: Ensure the user is logged in
  if (!session?.user?.id) {
    redirect("/");
  }

  // 1. Await the params to get the actual ID from the URL
  const { id } = await params;

  // 2. Fetch the specific file. 
  // We include ownerId in the where clause to prevent users from editing each other's files.
  const fileNode = await prisma.fileNode.findUnique({
    where: { 
      id: id,
      ownerId: session.user.id 
    }
  });

  if (!fileNode) {
    notFound();
  }

  // 3. Fetch folders for the destination dropdown (if you decide to allow moving files)
  const folders = await prisma.fileNode.findMany({
    where: { 
      isFolder: true,
      ownerId: session.user.id
    },
    orderBy: { name: 'asc' },
    select: { id: true, name: true }
  });

  // 4. Convert Decimal/BigInt fields to strings/numbers if necessary for client serialization
  const serializedFileNode = {
    ...fileNode,
    size: fileNode.size ? fileNode.size.toString() : "0" // BigInt cannot be passed directly to Client Components
    // metadata is already a JSON object, so it passes through fine
  };

  return (
    <Container maxWidth="md" sx={{ py: 8 }}>
      <UpdateView 
        fileNode={serializedFileNode} 
        folders={folders} 
      />
    </Container>
  );
}