import { getAuthenticatedUser } from "@/auth";
import { getUserExtension, getFollowMe, getVoicemailBox, getMohClasses } from "@/database/pbx";
import UserVoiceSettings from "@/components/account/UserVoiceSettings";

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

  let extension = null;
  let followMe = null;
  let voicemailBox = null;
  let mohClasses: Array<{ id: string; name: string; isDefault: boolean }> = [];

  if (user?.gscUserId && user.tenantId) {
    try {
      extension = await getUserExtension(user.gscUserId, user.tenantId);

      if (extension) {
        const [fm, vm, moh] = await Promise.all([
          getFollowMe(extension.id),
          getVoicemailBox(extension.id),
          getMohClasses(user.tenantId),
        ]);
        followMe = fm;
        voicemailBox = vm;
        mohClasses = moh;
      }
    } catch (err) {
      console.warn("[voice page] PBX fetch error:", err);
    }
  }

  return (
    <UserVoiceSettings
      extension={extension}
      followMe={followMe}
      voicemailBox={voicemailBox}
      mohClasses={mohClasses}
      tenantId={user?.tenantId || ""}
      userEmail={user?.email || ""}
    />
  );
}
