import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { Building2 } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { CompanyView, type Employee } from "@/components/dashboard/company-view";
import { CompanyGovernance } from "@/components/dashboard/company-governance";
import { CompanyDashboardCard } from "@/components/dashboard/company-dashboard-card";

export const dynamic = "force-dynamic";

export default async function CompanyPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) redirect("/login");

  const instances = await prisma.instance.findMany({
    where: { user_id: parseInt(session.user.id), app_type: "hermes" },
    include: { agent_role: true },
    orderBy: { created_at: "asc" },
  });

  const employees: Employee[] = instances.map((i) => ({
    id: i.id,
    name: i.name,
    status: i.status,
    subdomain: i.subdomain,
    deployment_mode: i.deployment_mode,
    role_name: i.agent_role?.name || null,
    role_name_ar: i.agent_role?.name_ar || null,
    role_icon: i.agent_role?.icon || null,
    notes: i.notes,
  }));

  return (
    <div dir="rtl" className="space-y-6">
      <div className="flex items-center gap-3">
        <span className="flex h-11 w-11 items-center justify-center rounded-lg bg-brand/10 text-brand">
          <Building2 size={22} />
        </span>
        <div>
          <h1 className="text-2xl font-bold text-ink">شركتي</h1>
          <p className="text-sm text-slate-500">أدر فريق موظفيك الذكيين — وزّع المهام، جدول الأعمال الدورية، وتابع الإنجاز.</p>
        </div>
      </div>
      {employees.some((e) => e.status === "RUNNING" && e.deployment_mode === "profile") && <CompanyDashboardCard />}
      <CompanyView employees={employees} />
      {employees.some((e) => e.status === "RUNNING") && <CompanyGovernance />}
    </div>
  );
}
