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

// 定义请求参数类型
interface RoomDeleteArgs {
  user: string;
  roomId: number;
}

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

// 处理 POST 请求
export async function POST(request: Request) {
  try {
    // 解析请求体
    const body: RoomDeleteArgs = await request.json();
    const { user, roomId } = body;
    
    // 验证参数
    if (!user || roomId === undefined || roomId === null) {
      return NextResponse.json({
        code: 2,
        message: '缺少必要参数: user 和 roomId 是必需的'
      } satisfies ApiResponse, {
        status: 400
      });
    }
    
    // 删除房间
    await deleteRoom(roomId, user);
    
    // 返回成功响应（无数据，code 0 表示成功）
    return NextResponse.json({
      code: 0
    } 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('无权')) {
      statusCode = 403;
      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. Use POST instead'
  } satisfies ApiResponse, {
    status: 405
  });
}

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