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/platform/workspaces/[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 { role?: string };

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

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

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

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

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

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

// DELETE /api/platform/workspaces/[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; role: string; user_id: string }>(
      `SELECT id, role, user_id FROM workspace_membership WHERE id = $1 AND workspace_id = $2`,
      [memberId, id]
    );
    if (!member.rows.length) {
      return NextResponse.json({ error: "成员不存在" }, { status: 404 });
    }
    if (member.rows[0].role === "owner") {
      return NextResponse.json({ error: "无法删除 Owner" }, { status: 403 });
    }

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

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "delete",
      resource: "workspace_member",
      resourceId: memberId,
      requestParams: { workspaceId: id, userId: member.rows[0].user_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 workspace member error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
