import { getAuthenticatedUser } from "@/auth";
import { getUserEffectiveSettings } from "@/database/settings";
import AccountSettings from "@/components/account/AccountSettings";

const SETTINGS_CATEGORIES = ["user.general", "user.notifications", "user.email", "user.calendar"];

export default async function SettingsPage() {
  const user = await getAuthenticatedUser();

  let initialSettings: Record<string, unknown> = {};

  if (user?.gscUserId) {
    try {
      const effective = await getUserEffectiveSettings(
        user.gscUserId,
        user.tenantId,
        user.gscCustomerId,
        SETTINGS_CATEGORIES
      );

      for (const cat of Object.values(effective)) {
        for (const [key, setting] of Object.entries(cat)) {
          initialSettings[key] = setting.value;
        }
      }
    } catch (err) {
      console.warn("[settings page] Failed to load settings:", err);
    }
  }

  return (
    <AccountSettings
      displayName={user?.displayName || "User"}
      email={user?.email || ""}
      initialSettings={initialSettings}
    />
  );
}
