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";

// GET /api/platform/workspaces/[id]/members
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const result = await query(
      `SELECT wm.id, wm.workspace_id, wm.user_id, wm.role, wm.status,
              wm.invited_by, wm.joined_at::text, wm.invite_token, wm.invite_expires_at::text,
              u.username, u.display_name, u.avatar_url,
              COALESCE(up.is_active, true) as user_is_active
       FROM workspace_membership wm
       JOIN "user" u ON u.uid = wm.user_id
       LEFT JOIN user_password up ON up.user = u.uid
       WHERE wm.workspace_id = $1
       ORDER BY wm.role = 'owner' DESC, wm.role = 'admin' DESC, wm.joined_at ASC`,
      [id]
    );

    const members = result.rows.map((r: Record<string, unknown>) => ({
      id: r.id,
      workspaceId: r.workspace_id,
      userId: r.user_id,
      role: r.role,
      status: r.status,
      invitedBy: r.invited_by,
      joinedAt: r.joined_at,
      inviteToken: r.invite_token,
      inviteExpiresAt: r.invite_expires_at,
      username: r.username,
      displayName: r.display_name,
      avatarUrl: r.avatar_url,
      userIsActive: r.user_is_active,
    }));

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

// POST /api/platform/workspaces/[id]/members — 添加成员
export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await req.json() as {
      userId?: string;
      role?: string;
    };

    if (!body.userId) {
      return NextResponse.json({ error: "缺少 userId" }, { status: 400 });
    }

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

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

    // 检查 workspace 是否存在
    const wsRow = await query<{ id: string }>(`SELECT id FROM workspace WHERE id = $1 AND deleted_at IS NULL`, [id]);
    if (!wsRow.rows.length) {
      return NextResponse.json({ error: "Workspace 不存在" }, { status: 404 });
    }

    // 检查用户是否存在
    const userRow = await query<{ uid: string }>(`SELECT uid FROM "user" WHERE uid = $1`, [body.userId]);
    if (!userRow.rows.length) {
      return NextResponse.json({ error: "用户不存在" }, { status: 404 });
    }

    // 检查是否已是成员
    const exist = await query(
      `SELECT id FROM workspace_membership WHERE workspace_id = $1 AND user_id = $2`,
      [id, body.userId]
    );
    if (exist.rows.length) {
      return NextResponse.json({ error: "该用户已是成员" }, { status: 409 });
    }

    const result = await query(
      `INSERT INTO workspace_membership (workspace_id, user_id, role, status, joined_at)
       VALUES ($1, $2, $3, 'active', NOW())
       RETURNING id`,
      [id, body.userId, role]
    );

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "create",
      resource: "workspace_member",
      resourceId: String(result.rows[0]?.id),
      requestParams: { workspaceId: id, userId: body.userId, role },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true, id: result.rows[0]?.id }, { status: 201 });
  } catch (e) {
    logError("Add workspace member error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
