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

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = req.nextUrl;
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const pageSize = Math.max(1, parseInt(searchParams.get("pageSize") || "20", 10));
    const search = searchParams.get("search") || "";
    const plan = searchParams.get("plan") || "";
    const offset = (page - 1) * pageSize;

    let whereClause = `WHERE w.deleted_at IS NULL`;
    const params: unknown[] = [];
    let idx = 1;

    if (search) {
      whereClause += ` AND (w.name ILIKE $${idx} OR w.slug ILIKE $${idx})`;
      params.push(`%${search}%`);
      idx++;
    }
    if (plan) {
      whereClause += ` AND w.plan = $${idx}`;
      params.push(plan);
      idx++;
    }

    const countResult = await query<{ count: string }>(
      `SELECT COUNT(*) FROM workspace w ${whereClause}`,
      params
    );
    const total = parseInt(countResult.rows[0]?.count || "0", 10);

    const limitParam = idx++;
    const offsetParam = idx++;
    const rows = await query(
      `SELECT
         w.id, w.slug, w.name, w.plan, w.description,
         w.billing_email, w.created_at, w.updated_at,
         wb.balance, wb.currency,
         COUNT(DISTINCT wm.user_id)::int as member_count,
         COUNT(DISTINCT p.id)::int as project_count
       FROM workspace w
       LEFT JOIN workspace_billing wb ON wb.workspace_id = w.id
       LEFT JOIN workspace_membership wm ON wm.workspace_id = w.id
       LEFT JOIN project p ON p.workspace_id = w.id
       ${whereClause}
       GROUP BY w.id, wb.balance, wb.currency
       ORDER BY w.created_at DESC
       LIMIT $${limitParam} OFFSET $${offsetParam}`,
      [...params, pageSize, offset]
    );

    return NextResponse.json({
      workspaces: rows.rows,
      total,
      page,
      pageSize,
    });
  } catch (e) {
    console.error("List workspaces error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function PATCH(req: NextRequest) {
  try {
    const body = await req.json() as {
      ids?: string[];
      plan?: string;
    };
    const { ids = [], plan } = body;

    if (!ids.length) {
      return NextResponse.json({ error: "至少选择一个 Workspace" }, { status: 400 });
    }
    if (!plan) {
      return NextResponse.json({ error: "plan 不能为空" }, { status: 400 });
    }

    const validPlans = ["free", "starter", "pro", "enterprise"];
    if (!validPlans.includes(plan)) {
      return NextResponse.json({ error: "无效的计划类型" }, { status: 400 });
    }

    const placeholders = ids.map((_, i) => `$${i + 1}`).join(", ");
    await query(
      `UPDATE workspace SET plan = $${ids.length + 1}, updated_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
      [...ids, plan]
    );

    const { searchParams } = req.headers.get("referer") ? new URL(req.headers.get("referer")!) : new URL("http://localhost/");
    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";
    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "update",
      resource: "workspace_batch_plan",
      resourceId: `batch(${ids.length})`,
      requestParams: { ids, plan },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true, updated: ids.length });
  } catch (e) {
    console.error("Batch update workspace plan error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
