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

// 定义请求参数类型
interface MessageAddArgs {
  roomId: number;
  content: string;
  sender: string;
}

// 定义响应类型
interface ApiResponse {
  code: number;
  message?: string;
  data?: {
    message?: Message;
  };
}

// 处理 POST 请求
export async function POST(request: Request) {
  try {
    // 解析请求体
    const body: MessageAddArgs = await request.json();
    const { roomId, content, sender } = body;
    
    // 验证参数
    if (!content || !sender || roomId === undefined) {
      return NextResponse.json({
        code: 2,
        message: '缺少必要参数: roomId, content 和 sender 是必需的'
      } satisfies ApiResponse, {
        status: 400
      });
    }
    
    // 添加消息
    const newMessage = await addMessage(roomId, content, sender);
    
    // 返回成功响应
    return NextResponse.json({
      code: 0,
      data: { message: newMessage }
    } satisfies ApiResponse, {
      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;
    } else if (error.message.includes('太短') || error.message.includes('太长')) {
      statusCode = 400;
      errorCode = 5;
      errorMessage = error.message;
    }
    
    return NextResponse.json({
      code: errorCode,
      message: errorMessage
    } satisfies ApiResponse, {
      status: statusCode
    });
  }
}

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

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

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