import { redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"
import PageShell from "@/components/app/PageShell"
import EmployeeDashboard from "@/features/dashboard/EmployeeDashboard"

const prisma = db as PrismaClient as unknown as any

export const dynamic = "force-dynamic"


function resolveRoleNames(rawRoles: any[]): string[] {
  return rawRoles.map((r: any) => {
    if (typeof r === "string") return r.toUpperCase()
    if (typeof r?.name === "string") return r.name.toUpperCase()
    if (typeof r?.role?.name === "string") return r.role.name.toUpperCase()
    return ""
  }).filter(Boolean)
}

export default async function EmployeePortalPage() {
  const session = await auth()
  if (!session?.user?.id) redirect("/login")

  const rawRoles = Array.isArray((session.user as any).roles)
    ? (session.user as any).roles
    : []
  const roleNames = resolveRoleNames(rawRoles)

  console.log("[employee portal] roleNames:", roleNames)

  // If NOT an employee role at all, send to admin dashboard
  if (!roleNames.includes("EMPLOYEE")) {
    redirect("/dashboard")
  }

  const employee = await prisma.employee.findFirst({
    where: { userId: session.user.id },
    include: {
      branch:           { select: { id: true, name: true } },
      department:       { select: { id: true, name: true } },
      subDepartment:    { select: { id: true, name: true } },
      reportingManager: { select: { id: true, fullName: true, position: true, avatarUrl: true } },
      shifts: {
        include:  { shift: true },
        orderBy:  { effectiveFrom: "desc" },
        take: 1,
      },
      salaryComponents: true,
      leaveAllowances:  { include: { leaveType: true } },
      leaveRequests: {
        include:  { leaveType: true },
        orderBy:  { createdAt: "desc" },
        take: 10,
      },
      payrolls: {
        orderBy: [{ year: "desc" }, { month: "desc" }],
        take: 6,
        include: { items: true },
      },
      attendances: {
        orderBy: { date: "desc" },
        take: 31,
      },
      document: true,
    },
  })

  if (!employee) {
    return (
      <PageShell>
        <div className="flex flex-col items-center justify-center min-h-[60vh] text-center gap-3">
          <h2 className="text-xl font-semibold">No Employee Profile Found</h2>
          <p className="text-muted-foreground text-sm max-w-sm">
            Your account isn't linked to an employee record yet. Please contact HR.
          </p>
        </div>
      </PageShell>
    )
  }

  return (
    <PageShell>
      <EmployeeDashboard employee={employee} />
    </PageShell>
  )
}