import AttendanceRegister from "@/features/attendance/components/AttendanceRegister"
import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"

const prisma = db as PrismaClient as unknown as any

const departments = await db.department.findMany({
  select: { id: true, name: true, branchId: true }
})

export default async function AttendancePage() {
  const [employees, branches] = await Promise.all([
    prisma.employee.findMany({
      orderBy: { fullName: "asc" },
      select: { id: true, fullName: true, branchId: true, departmentId: true, position: true, zktecoId: true }
    }),
    prisma.branch.findMany({ orderBy: { name: "asc" } }),
  ])

  // If duplicates exist (often due to non-unique zktecoId), keep one row per zktecoId.
  // Prefer the record that has a branch assigned.
  const dedupedEmployees = (() => {
    const map = new Map<string, (typeof employees)[number]>()
    for (const e of employees) {
      const key = (e?.zktecoId as string | null | undefined) ?? e.id
      const existing = map.get(key)
      if (!existing) {
        map.set(key, e)
        continue
      }
      if (!existing.branchId && e.branchId) map.set(key, e)
    }
    return Array.from(map.values())
  })()

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Attendance</h1>
        <p className="text-sm text-muted-foreground">
          Click any cell to mark attendance. Use the branch filter and month navigator to switch views.
        </p>
      </div>

      <AttendanceRegister
        employees={dedupedEmployees}
        branches={branches}
        departments={departments}
      />
    </div>
  )
}