import { ProfileSettings } from "@/features/profile/profile-settings";
import { getCurrentUserProfile } from "@/features/profile/api";
import type { UserProfile } from "@/features/profile/contract";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import { getServerSession } from "@/lib/auth/server-session";
import { roles } from "@/features/auth/validation";

export const metadata = { title: "Profile Settings" };

export default async function ProfilePage() {
  const session = isCsmsApiConfigured() ? await getServerSession() : null;
  const roleLabel = roles.find((role) => role.value === session?.role)?.label;
  if (!isCsmsApiConfigured()) {
    return <ProfileSettings profile={null} loadError="Profile settings require a connected CSMS API." />;
  }

  let profile: UserProfile | null = null;
  let loadError: string | undefined;
  try {
    profile = await getCurrentUserProfile();
  } catch (error) {
    loadError = error instanceof Error ? error.message : "Unable to load your profile.";
  }
  return <ProfileSettings
    profile={profile}
    roleLabel={roleLabel}
    tenantCode={session?.tenantCode}
    loadError={loadError}
  />;
}
