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") || "30", 10));
    const projectId = searchParams.get("projectId") || "";
    const search = searchParams.get("search") || "";
    const offset = (page - 1) * pageSize;

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

    if (projectId) {
      conditions.push(`r.project = $${paramIdx++}`);
      params.push(projectId);
    }
    if (search) {
      conditions.push(`r.room_name ILIKE $${paramIdx++}`);
      params.push(`%${search}%`);
    }

    const whereCond = conditions.join(" AND ");
    const limitIdx = paramIdx++;
    const offsetIdx = paramIdx++;

    const [roomsResult, countResult] = await Promise.all([
      query<{
        id: string;
        room_name: string;
        is_public: boolean;
        project_id: string;
        project_name: string;
        workspace_name: string;
        created_by: string;
        created_at: Date;
        last_msg_at: Date;
        member_count: string;
        message_count: string;
      }>(
        `SELECT
           r.id, r.room_name, r.public as is_public,
           r.project as project_id,
           p.name as project_name,
           COALESCE(w.name, '') as workspace_name,
           r.created_by::text as created_by,
           r.created_at::text as created_at,
           r.last_msg_at::text as last_msg_at,
           COUNT(DISTINCT rm.user)::text as member_count,
           (SELECT COUNT(*) FROM room_message WHERE room = r.id AND revoked IS NULL)::text as message_count
         FROM room r
         JOIN project p ON p.id = r.project
         LEFT JOIN workspace w ON w.id = p.workspace_id
         LEFT JOIN room_member rm ON rm.room = r.id
         WHERE ${whereCond}
         GROUP BY r.id, p.name, w.name
         ORDER BY r.last_msg_at DESC
         LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
        [...params, pageSize, offset]
      ),
      query<{ count: string }>(
        `SELECT COUNT(DISTINCT r.id)::text as count
         FROM room r
         JOIN project p ON p.id = r.project
         WHERE ${whereCond}`,
        params
      ),
    ]);

    const rooms = roomsResult.rows.map((r) => ({
      id: r.id,
      roomName: r.room_name,
      isPublic: r.is_public,
      projectId: r.project_id,
      projectName: r.project_name,
      workspaceName: r.workspace_name,
      createdBy: r.created_by,
      createdAt: String(r.created_at),
      lastMsgAt: String(r.last_msg_at),
      memberCount: parseInt(r.member_count || "0", 10),
      messageCount: parseInt(r.message_count || "0", 10),
    }));

    const total = parseInt(countResult.rows[0]?.count || "0", 10);

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