import { getDashboardStats, getRegistrations } from '@/lib/actions/admin';
import AdminDashboardClient from '@/components/admin/AdminDashboardClient';
import { createClient } from '@/lib/supabase/server';
import { createClient as createAdminClient } from '@supabase/supabase-js';
import { redirect } from 'next/navigation';

export const metadata = {
  title: 'Admin Dashboard | TechTan Ignite-100',
};

export default async function AdminPage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    redirect('/admin/login');
  }

  // Verify admin role in profiles table
  const supabaseAdmin = createAdminClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    { auth: { autoRefreshToken: false, persistSession: false } }
  );

  const { data: profile } = await supabaseAdmin
    .from('profiles')
    .select('role')
    .eq('id', user.id)
    .single();

  if (!profile || profile.role !== 'admin') {
    redirect('/admin/login?error=unauthorized');
  }

  const [stats, registrations] = await Promise.all([
    getDashboardStats(),
    getRegistrations(),
  ]);

  return <AdminDashboardClient stats={stats} registrations={registrations} />;
}