import { tasksService } from '@/services/task-management/tasks';
import { tagsService } from '@/services/task-management/tags';
import { backupService } from '@/services/data-management/backup';
import { backupScheduler } from '@/services/data-management/backup-scheduler';
import { AdvancedSettingsPageClient } from '@/components/settings/AdvancedSettingsPageClient';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

// Force dynamic rendering for real-time data
export const dynamic = 'force-dynamic';

export default async function AdvancedSettingsPage() {
  // Récupérer l'utilisateur connecté
  const session = await getServerSession(authOptions);
  const userId = session?.user?.id;

  // Si pas d'utilisateur connecté, retourner une page vide
  if (!userId) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Connexion requise</h1>
          <p className="text-gray-600">
            Veuillez vous connecter pour accéder aux paramètres avancés.
          </p>
        </div>
      </div>
    );
  }

  // Fetch all data server-side
  const [taskStats, tags] = await Promise.all([
    tasksService.getTaskStats(userId),
    tagsService.getTags(userId),
  ]);

  // Compose backup data like the API does
  const backups = await backupService.listBackups();
  const schedulerStatus = backupScheduler.getStatus();
  const config = await backupService.getConfig();

  const backupData = {
    backups,
    scheduler: {
      ...schedulerStatus,
      nextBackup: schedulerStatus.nextBackup?.toISOString() || null,
    },
    config,
  };

  const dbStats = {
    taskCount: taskStats.total,
    tagCount: tags.length,
    completionRate: taskStats.completionRate,
  };

  return (
    <AdvancedSettingsPageClient
      initialDbStats={dbStats}
      initialBackupData={backupData}
    />
  );
}
