import { NextRequest, NextResponse } from "next/server";
import {
  listUsers,
  createUser,
  setUserRoles,
} from "@/lib/rbac";
import { createAuditLog } from "@/lib/log";
import { hashPassword } from "@/lib/auth";

function getAuthInfo(req: NextRequest) {
  return {
    userId: parseInt(req.headers.get("x-admin-user-id") || "0", 10),
    username: req.headers.get("x-admin-username") || "unknown",
  };
}

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = req.nextUrl;
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const pageSize = Math.max(1, parseInt(searchParams.get("pageSize") || "20", 10));
    const search = searchParams.get("search") || undefined;

    const result = await listUsers({ page, pageSize, search });
    return NextResponse.json(result);
  } catch (e) {
    console.error("List users error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json() as {
      username?: string;
      password?: string;
      roleIds?: number[];
    };
    const { username = "", password = "" } = body;

    if (!username || !password) {
      return NextResponse.json({ error: "用户名和密码不能为空" }, { status: 400 });
    }

    if (password.length < 6) {
      return NextResponse.json({ error: "密码长度至少6位" }, { status: 400 });
    }

    const passwordHash = await hashPassword(password);
    const user = await createUser(username, passwordHash);

    if (body.roleIds?.length) {
      await setUserRoles(user.id, body.roleIds);
    }

    const { userId, username: actorName } = getAuthInfo(req);
    await createAuditLog({
      userId,
      username: actorName,
      action: "create",
      resource: "admin_user",
      resourceId: String(user.id),
      requestParams: { username },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json(user, { status: 201 });
  } catch (e: unknown) {
    if ((e as { code?: string }).code === "23505") {
      return NextResponse.json({ error: "用户名已存在" }, { status: 409 });
    }
    console.error("Create user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
