import sql from '@/lib/db'
import { App } from '@/types'
import { Navbar } from '@/components/Navbar'
import { DashboardClient } from '@/components/DashboardClient'

export const dynamic = 'force-dynamic'

async function getDashboardData() {
  const apps = await sql`
    SELECT a.*, COUNT(ce.id) as config_count 
    FROM apps a 
    LEFT JOIN environments e ON e.app_id = a.id 
    LEFT JOIN config_entries ce ON ce.environment_id = e.id 
    GROUP BY a.id 
    ORDER BY a.created_at DESC
  ` as any

  const [totalConfigs] = await sql`SELECT count(*)::int as count FROM config_entries`
  const [totalAudit] = await sql`SELECT count(*)::int as count FROM audit_logs`

  return {
    apps,
    totalConfigsCount: totalConfigs?.count || 0,
    totalAuditCount: totalAudit?.count || 0,
  }
}

export default async function DashboardPage() {
  const { apps, totalConfigsCount, totalAuditCount } = await getDashboardData()

  return (
    <div className="min-h-screen pb-16">
      <Navbar />

      <main className="max-w-7xl mx-auto px-4 sm:px-6 pt-8">
        <DashboardClient
          initialApps={apps}
          totalConfigsCount={totalConfigsCount}
          totalAuditCount={totalAuditCount}
        />
      </main>
    </div>
  )
}
