import { getQuestSession, getActiveCompany } from '@/lib/permissions';
import { PortalSidebar } from '@/components/layout/portal-sidebar';
import { PortalHeader } from '@/components/layout/portal-header';
import { Breadcrumb } from '@/components/layout/breadcrumb';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';

export default async function PortalLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // Check authentication
  const session = await getQuestSession();

  if (!session) {
    redirect('/login');
  }

  // Get active company
  const activeCompany = await getActiveCompany();

  // Get unread notifications count
  const unreadNotifications = await db.quest_user_notification_alert_read.count(
    {
      where: {
        auth_user_id: session.user.id,
      },
    }
  );

  const isAdmin =
    session.userType === 'Admin' || session.userType === 'Super Admin';

  return (
    <div className="flex min-h-screen">
      <PortalSidebar isAdmin={isAdmin} permissions={session.permissionRules} />
      <div className="flex-1 pl-64">
        <PortalHeader
          companyName={activeCompany?.display_name}
          isAdmin={isAdmin}
          unreadNotifications={unreadNotifications}
        />
        <main className="p-6">
          <Breadcrumb />
          {children}
        </main>
      </div>
    </div>
  );
}
