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

export const runtime = "nodejs";

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

    const result = await query(
      `SELECT pm.id, pm.project_uuid, pm.user_uuid, pm.scope, pm.joined_at::text,
              u.username, u.display_name, u.avatar_url,
              COALESCE(up.is_active, true) as user_is_active
       FROM project_members pm
       JOIN "user" u ON u.uid = pm.user_uuid
       LEFT JOIN user_password up ON up.user = u.uid
       WHERE pm.project_uuid = $1
       ORDER BY pm.scope = 'owner' DESC, pm.scope = 'admin' DESC, pm.joined_at ASC`,
      [id]
    );

    const members = result.rows.map((r: Record<string, unknown>) => ({
      id: r.id,
      projectId: r.project_uuid,
      userId: r.user_uuid,
      scope: r.scope,
      joinedAt: r.joined_at,
      username: r.username,
      displayName: r.display_name,
      avatarUrl: r.avatar_url,
      userIsActive: r.user_is_active,
    }));

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

// POST /api/admin/projects/[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;
      scope?: 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 scope = body.scope || "member";
    if (!["owner", "admin", "member"].includes(scope)) {
      return NextResponse.json({ error: "无效的角色" }, { status: 400 });
    }

    // 检查 project 是否存在
    const projRow = await query<{ id: string }>(`SELECT id FROM project WHERE id = $1`, [id]);
    if (!projRow.rows.length) {
      return NextResponse.json({ error: "项目不存在" }, { 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 project_members WHERE project_uuid = $1 AND user_uuid = $2`,
      [id, body.userId]
    );
    if (exist.rows.length) {
      return NextResponse.json({ error: "该用户已是成员" }, { status: 409 });
    }

    const result = await query(
      `INSERT INTO project_members (project_uuid, user_uuid, scope, joined_at)
       VALUES ($1, $2, $3, NOW())
       RETURNING id`,
      [id, body.userId, scope]
    );

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "create",
      resource: "project_member",
      resourceId: String(result.rows[0]?.id),
      requestParams: { projectId: id, userId: body.userId, scope },
      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) {
    console.error("Add project member error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
