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

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 workspaceId = searchParams.get("workspaceId") || "";
    const visibility = searchParams.get("visibility") || "";

    const offset = (page - 1) * pageSize;

    const params: (string | number)[] = [];
    let paramIdx = 1;

    let where = "WHERE 1=1";
    if (search) {
      where += ` AND (p.name ILIKE $${paramIdx} OR p.display_name ILIKE $${paramIdx})`;
      params.push(`%${search}%`);
      paramIdx++;
    }
    if (workspaceId) {
      where += ` AND p.workspace_id = $${paramIdx}`;
      params.push(workspaceId);
      paramIdx++;
    }
    if (visibility) {
      where += ` AND p.is_public = $${paramIdx}`;
      params.push(visibility === "public" ? 1 : 0);
      paramIdx++;
    }

    const limitParam = paramIdx;
    const offsetParam = paramIdx + 1;

    const countResult = await query(
      `SELECT COUNT(*) as total FROM project p ${where}`,
      params
    );
    const total = parseInt(String(countResult.rows[0].total), 10);

    params.push(pageSize, offset);

    const projects = await query(
      `SELECT p.id, p.name, p.display_name, p.description, p.is_public, p.workspace_id,
              p.created_by, p.created_at, p.updated_at,
              w.name as workspace_name, w.slug as workspace_slug,
              COALESCE(b.balance, 0)::text as balance, COALESCE(b.currency, 'USD') as currency,
              COUNT(DISTINCT pm.user_uuid) as member_count
       FROM project p
       LEFT JOIN workspace w ON w.id = p.workspace_id
       LEFT JOIN project_billing b ON b.project_uuid = p.id
       LEFT JOIN project_members pm ON pm.project_uuid = p.id
       ${where}
       GROUP BY p.id, w.name, w.slug, b.balance, b.currency
       ORDER BY p.created_at DESC
       LIMIT $${limitParam} OFFSET $${offsetParam}`,
      params
    );

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