import { NextResponse } from 'next/server';
import { getRoomMessages } from '@/server/db/index';
import type { Message } from "@/types";

// Define the response type
interface RoomMessageListRes {
  code: number;
  message?: string;
  data?: {
    messages: Message[];
  };
}

// Handle GET requests
export async function GET(request: Request) {
  try {
    // From URL, parse query parameters
    const { searchParams } = new URL(request.url);
    const roomId = Number(searchParams.get('roomId'));
    
    // Validate parameters
    if (isNaN(roomId) || roomId <= 0) {
      return NextResponse.json({
        code: 2,
        message: 'Parameter error: roomId must be a positive integer'
      } satisfies RoomMessageListRes, {
        status: 400
      });
    }
    
    // Get the message list
    // FIX: Add the 'await' keyword here
    const messages = await getRoomMessages(roomId);
    
    // Return a successful response
    return NextResponse.json({
      code: 0,
      data: { messages } // `messages` is now correctly an array
    } satisfies RoomMessageListRes);
    
  } catch (error: any) {
    console.error('Failed to get message list:', error);
    
    // Return different error codes based on the error type
    let statusCode = 500;
    let errorCode = 3;
    let errorMessage = 'Internal server error';
    
    if (error.message.includes('不存在')) { // "does not exist"
      statusCode = 404;
      errorCode = 4;
      errorMessage = error.message;
    }
    
    return NextResponse.json({
      code: errorCode,
      message: errorMessage
    } satisfies RoomMessageListRes, {
      status: statusCode
    });
  }
}

// 处理其他不允许的方法
export async function POST() {
  return NextResponse.json({
    code: 1,
    message: 'Method not allowed. Use GET instead'
  } satisfies RoomMessageListRes, {
    status: 405
  });
}

export async function PUT() {
  return NextResponse.json({
    code: 1,
    message: 'Method not allowed'
  } satisfies RoomMessageListRes, {
    status: 405
  });
}

export async function DELETE() {
  return NextResponse.json({
    code: 1,
    message: 'Method not allowed'
  } satisfies RoomMessageListRes, {
    status: 405
  });
}