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

export const runtime = "nodejs";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const [workspace, members, projects, billing] = await Promise.all([
      query(
        `SELECT w.*, wb.balance, wb.currency, wb.monthly_quota, wb.total_spent
         FROM workspace w
         LEFT JOIN workspace_billing wb ON wb.workspace_id = w.id
         WHERE w.id = $1 AND w.deleted_at IS NULL`,
        [id]
      ),
      query(
        `SELECT wm.id, u.uid, u.username, u.display_name, u.avatar_url,
                wm.role, wm.status, wm.joined_at
         FROM workspace_membership wm
         JOIN "user" u ON u.uid = wm.user_id
         WHERE wm.workspace_id = $1
         ORDER BY wm.role = 'owner' DESC, wm.role = 'admin' DESC, wm.joined_at ASC`,
        [id]
      ),
      query(
        `SELECT p.id, p.name, p.is_public, p.created_at,
                COUNT(DISTINCT pm.user_uuid)::int as member_count
         FROM project p
         LEFT JOIN project_members pm ON pm.project_uuid = p.id
         WHERE p.workspace_id = $1
         GROUP BY p.id
         ORDER BY p.created_at DESC
         LIMIT 50`,
        [id]
      ),
      query(
        `SELECT reason, amount, extra as description, created_at
         FROM workspace_billing_history
         WHERE workspace_id = $1
         ORDER BY created_at DESC
         LIMIT 50`,
        [id]
      ),
    ]);

    if (!workspace.rows.length) {
      return NextResponse.json({ error: "Workspace 不存在" }, { status: 404 });
    }

    return NextResponse.json({
      workspace: workspace.rows[0],
      members: members.rows,
      projects: projects.rows,
      billingHistory: billing.rows,
    });
  } catch (e) {
    console.error("Workspace detail error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
