import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { createAuditLog } from "@/lib/log";

export const runtime = "nodejs";

// PATCH /api/admin/projects/[id]/members/[memberId]
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string; memberId: string }> }
) {
  try {
    const { id, memberId } = await params;
    const body = await req.json() as { scope?: string };

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";

    if (body.scope && !["owner", "admin", "member"].includes(body.scope)) {
      return NextResponse.json({ error: "无效的角色" }, { status: 400 });
    }

    const member = await query<{ id: string; scope: string; user_uuid: string }>(
      `SELECT id, scope, user_uuid FROM project_members WHERE id = $1 AND project_uuid = $2`,
      [memberId, id]
    );
    if (!member.rows.length) {
      return NextResponse.json({ error: "成员不存在" }, { status: 404 });
    }
    if (member.rows[0].scope === "owner") {
      return NextResponse.json({ error: "无法修改 Owner 的角色" }, { status: 403 });
    }

    if (body.scope) {
      await query(`UPDATE project_members SET scope = $1 WHERE id = $2`, [body.scope, memberId]);
    }

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "update",
      resource: "project_member",
      resourceId: memberId,
      requestParams: { projectId: id, scope: body.scope },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

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

// DELETE /api/admin/projects/[id]/members/[memberId]
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string; memberId: string }> }
) {
  try {
    const { id, memberId } = await params;

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";

    const member = await query<{ id: string; scope: string; user_uuid: string }>(
      `SELECT id, scope, user_uuid FROM project_members WHERE id = $1 AND project_uuid = $2`,
      [memberId, id]
    );
    if (!member.rows.length) {
      return NextResponse.json({ error: "成员不存在" }, { status: 404 });
    }
    if (member.rows[0].scope === "owner") {
      return NextResponse.json({ error: "无法删除 Owner" }, { status: 403 });
    }

    await query(`DELETE FROM project_members WHERE id = $1`, [memberId]);

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "delete",
      resource: "project_member",
      resourceId: memberId,
      requestParams: { projectId: id, userId: member.rows[0].user_uuid },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

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