import { NextResponse } from 'next/server';
import { addRoom } from '@/server/db/index';

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

// 处理 POST 请求
export async function POST(request: Request) {
  try {
    // 解析请求体
    const body = await request.json();
    const { user, roomName } = body;
    
    // 验证参数
    if (!user || !roomName) {
      return NextResponse.json({
        code: 2,
        message: 'Missing parameters: user and roomName are required'
      } satisfies ApiResponse, {
        status: 400
      });
    }
    
    // 添加房间 - 添加 await 关键字
    const roomId = await addRoom(roomName, user);
    
    // 返回成功响应
    return NextResponse.json({
      code: 0,
      data: { roomId }
    } satisfies ApiResponse, {
      status: 200
    });
    
  } catch (error) {
    console.error('添加房间失败:', error);
    
    return NextResponse.json({
      code: 3,
      message: 'Internal server error'
    } satisfies ApiResponse, {
      status: 500
    });
  }
}

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

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

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