import { ProjectShell } from "@/components/layout/project-shell";
import { query } from "@/lib/db-postgres";

interface ProjectData {
  name: string;
  status?: string;
  progress?: number;
}

async function getProjectData(projectId: string): Promise<ProjectData> {
  try {
    const rows = await query<{ data: any }>(
      `SELECT data FROM fs_projects WHERE id = $1 LIMIT 1`,
      [projectId]
    );
    if (rows.length > 0) {
      const data = rows[0].data;
      return {
        name: data?.productName || data?.name || "Project",
        status: data?.status,
        progress: data?.progress ?? 0,
      };
    }
  } catch (error) {
    console.error("Error fetching project:", error);
  }
  return { name: "Project" };
}

export default async function ProjectLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ workspace: string; projectId: string }>;
}) {
  const { workspace, projectId } = await params;
  const project = await getProjectData(projectId);

  return (
    <ProjectShell
      workspace={workspace}
      projectId={projectId}
      projectName={project.name}
      projectStatus={project.status}
      projectProgress={project.progress}
    >
      {children}
    </ProjectShell>
  );
}
