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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { searchParams } = req.nextUrl;
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const pageSize = Math.max(1, parseInt(searchParams.get("pageSize") || "50", 10));
    const offset = (page - 1) * pageSize;

    const [messagesResult, countResult] = await Promise.all([
      query<{
        id: string;
        seq: string;
        sender_type: string;
        sender_id: string | null;
        sender_name: string | null;
        content: string;
        content_type: string;
        send_at: Date;
        revoked: Date | null;
        in_reply_to: string | null;
      }>(
        `SELECT
           m.id, m.seq, m.sender_type, m.sender_id,
           CASE
             WHEN m.sender_type = 'member' THEN COALESCE(u.display_name, u.username)
             WHEN m.sender_type = 'ai' THEN 'AI'
             WHEN m.sender_type = 'system' THEN 'System'
             ELSE m.sender_id::text
           END as sender_name,
           CASE
             WHEN m.sender_type = 'member' THEN 'user'
             ELSE m.sender_type
           END as sender_type,
           m.content, m.content_type, m.send_at::text as send_at,
           m.revoked::text as revoked,
           m.in_reply_to::text as in_reply_to
         FROM room_message m
         LEFT JOIN "user" u ON u.uid = m.sender_id
         WHERE m.room = $1
         ORDER BY m.seq DESC
         LIMIT $2 OFFSET $3`,
        [id, pageSize, offset]
      ),
      query<{ count: string }>(
        `SELECT COUNT(*)::text as count FROM room_message WHERE room = $1`,
        [id]
      ),
    ]);

    const messages = messagesResult.rows.map((m) => ({
      id: m.id,
      seq: parseInt(m.seq, 10),
      senderType: m.sender_type,
      senderId: m.sender_id,
      senderName: m.sender_name,
      content: m.content,
      contentType: m.content_type,
      sendAt: String(m.send_at),
      revoked: m.revoked ? String(m.revoked) : null,
      inReplyTo: m.in_reply_to,
    }));

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

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