import { AdminUsersManager } from "@/components/admin/admin-users-manager"
import { AppShell } from "@/components/app-shell"
import { SiteHeader } from "@/components/site-header"
import { ROLE_OPTIONS, normalizeRole, type RoleOption } from "@/lib/authz"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"
import { normalizeInvite, type NormalizedInvite } from "@/server/invite-utils"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

async function loadUsers() {
  const users = await prisma.authUser.findMany({
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      email: true,
      name: true,
      role: true,
      tenantId: true,
      createdAt: true,
      updatedAt: true,
    },
  })

  return users.map((user) => ({
    id: user.id,
    email: user.email,
    name: user.name ?? "",
    role: (normalizeRole(user.role) ?? "agent") as RoleOption,
    tenantId: user.tenantId ?? DEFAULT_TENANT_ID,
    createdAt: user.createdAt.toISOString(),
    updatedAt: user.updatedAt?.toISOString() ?? null,
  }))
}

async function loadInvites(): Promise<NormalizedInvite[]> {
  const invites = await prisma.authInvite.findMany({
    orderBy: { createdAt: "desc" },
    include: {
      events: {
        orderBy: { createdAt: "asc" },
      },
    },
  })

  const now = new Date()
  return invites.map((invite) => normalizeInvite(invite, now))
}

export default async function AdminPage() {
  const users = await loadUsers()
  const invites = await loadInvites()
  const invitesForClient = invites.map((invite) => {
    const { events, ...rest } = invite
    void events
    return rest
  })

  return (
    <AppShell
      header={
        <SiteHeader
          title="Administração"
          lead="Convide novos membros, ajuste papéis e organize as filas e categorias de atendimento."
        />
      }
    >
      <div className="mx-auto w-full max-w-6xl px-6 lg:px-8">
        <AdminUsersManager
          initialUsers={users}
          initialInvites={invitesForClient}
          roleOptions={ROLE_OPTIONS}
          defaultTenantId={DEFAULT_TENANT_ID}
        />
      </div>
    </AppShell>
  )
}
