import { db } from "@/db/client";
import { adminUsers } from "@/db/schema";
import { getCurrentUser, requireSuperAdmin } from "@/lib/auth";
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import AdminUsersClient from "./AdminUsersClient";

export const metadata = { title: "管理员管理" };

async function createAdminAction(formData: FormData) {
  "use server";
  await requireSuperAdmin();
  const name = String(formData.get("name") || "").trim();
  const email = String(formData.get("email") || "").trim();
  const roleRaw = String(formData.get("role") || "admin");
  const role = roleRaw === 'super' ? 'super' : 'admin';
  const isActive = formData.get("isActive") ? true : false;
  const password = String(formData.get("password") || "");
  if (!email || !password) return;
  const { hashPassword } = await import("@/lib/password");
  const passwordHash = await hashPassword(password);
  await db.insert(adminUsers).values({ name, email, passwordHash, role, isActive });
}

async function updateAdminAction(formData: FormData) {
  "use server";
  const me = await requireSuperAdmin();
  const id = Number(formData.get("id"));
  const name = String(formData.get("name") || "").trim();
  const roleRaw = String(formData.get("role") || "");
  const role = roleRaw === 'super' ? 'super' : roleRaw === 'admin' ? 'admin' : undefined;
  const isActive = formData.get("isActive") ? true : false;
  if (!id) return;
  if (id === me.id) {
    // 禁止修改自己的状态与角色，仅允许修改姓名
    await db.update(adminUsers).set({ name }).where(eq(adminUsers.id, id));
  } else {
    await db.update(adminUsers).set({ name, role: role ?? 'admin', isActive }).where(eq(adminUsers.id, id));
  }
}

export default async function AdminUsersPage() {
  const user = await getCurrentUser();
  if (!user) redirect('/signin');
  if (user.role !== 'super') redirect('/books');
  const users = await db.select().from(adminUsers).orderBy(adminUsers.id);
  return (
    <AdminUsersClient
      users={users as any}
      currentUserId={user.id}
      createAdminAction={createAdminAction}
      updateAdminAction={updateAdminAction}
    />
  );
}
