﻿import { createServerClient, requireAuth } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import type { Metadata } from 'next'
import { DashboardShell } from '@/components/layout/DashboardShell'
import { Providers } from '@/components/providers/Providers'
import { AGENT_API_URL } from '@/lib/api/config'

export const metadata: Metadata = {
  title: 'Dashboard',
  robots: { index: false, follow: false },
}

const API_BASE = AGENT_API_URL

async function isPlatformAdmin(): Promise<boolean> {
  try {
    const supabase = await createServerClient()
    const { data } = await supabase.auth.getSession()
    const token = data.session?.access_token
    if (!token) return false
    const res = await fetch(`${API_BASE}/agent/me`, {
      headers: { Authorization: `Bearer ${token}` },
      cache: 'no-store',
    })
    if (!res.ok) return false
    const body = await res.json()
    return body?.success === true && body?.data?.role === 'platform_admin'
  } catch {
    return false
  }
}

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode
}) {
  let user = null
  try {
    const supabase = await createServerClient()
    const result = await supabase.auth.getUser()
    user = result.data.user
  } catch {
    // Invalid/expired refresh token — treat as unauthenticated
  }

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

  // Platform admins have no business context — steer them to the control plane.
  if (await isPlatformAdmin()) {
    redirect('/platform')
  }

  return (
    <Providers>
      <DashboardShell>{children}</DashboardShell>
    </Providers>
  )
}