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

// 定义统一响应类型
interface UnifiedResponse {
  message: string;
  code: number;
  data: RoomMessageGetUpdateRes | null;
}

// 定义响应数据类型
interface RoomMessageGetUpdateRes {
  messages: Message[];
}

// 处理 GET 请求
export async function GET(request: Request) {
  try {
    // 解析查询参数
    const url = new URL(request.url);
    const roomId = parseInt(url.searchParams.get('roomId') || '');
    const sinceMessageId = parseInt(url.searchParams.get('sinceMessageId') || '0');
    
    // 验证参数
    if (isNaN(roomId) || isNaN(sinceMessageId)) {
      return NextResponse.json({
        message: '参数格式错误: roomId 和 sinceMessageId 必须是数字',
        code: 2,
        data: null
      } satisfies UnifiedResponse, {
        status: 400
      });
    }
    
    // 获取更新的消息
    const messages = await getUpdatedMessages(roomId, sinceMessageId);
    
    // 返回成功响应
    return NextResponse.json({
      message: '',
      code: 0,
      data: {
        messages
      }
    } satisfies UnifiedResponse, {
      status: 200
    });
    
  } catch (error: any) {
    console.error('获取消息更新失败:', error);
    
    // 根据错误类型返回不同的错误码
    let statusCode = 500;
    let errorCode = 3;
    let errorMessage = '内部服务器错误';
    
    if (error.message.includes('不存在')) {
      statusCode = 404;
      errorCode = 4;
      errorMessage = error.message;
    }
    
    return NextResponse.json({
      message: errorMessage,
      code: errorCode,
      data: null
    } satisfies UnifiedResponse, {
      status: statusCode
    });
  }
}

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

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

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