import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import {
  getUserById,
  updateUser,
  deleteUser,
  getUserRoles,
  setUserRoles,
} from "@/lib/rbac";
import { hashPassword } from "@/lib/auth";
import { createAuditLog } from "@/lib/log";

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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const userId = parseInt(id, 10);
    const user = await getUserById(userId);
    if (!user) return NextResponse.json({ error: "用户不存在" }, { status: 404 });

    // 不返回密码哈希
    const { password_hash: _, ...safeUser } = user;
    const roles = await getUserRoles(userId);

    return NextResponse.json({ ...safeUser, roles });
  } catch (e) {
    logError("Get user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const userId = parseInt(id, 10);
    const body = await req.json() as {
      password?: string;
      isActive?: boolean;
      roleIds?: number[];
    };

    const passwordHash = body.password
      ? await hashPassword(body.password)
      : undefined;

    const user = await updateUser(userId, {
      passwordHash,
      isActive: body.isActive,
    });

    if (!user) return NextResponse.json({ error: "用户不存在" }, { status: 404 });

    if (body.roleIds !== undefined) {
      await setUserRoles(userId, body.roleIds);
    }

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

    const { password_hash: _, ...safeUser } = user;
    return NextResponse.json(safeUser);
  } catch (e) {
    logError("Update user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const userId = parseInt(id, 10);

    if (userId === -1) {
      return NextResponse.json({ error: "无法删除超级管理员" }, { status: 400 });
    }

    const ok = await deleteUser(userId);
    if (!ok) return NextResponse.json({ error: "用户不存在" }, { status: 404 });

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

    return NextResponse.json({ success: true });
  } catch (e) {
    logError("Delete user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
