import { BadRequestException, Body, Controller, Get, HttpStatus, Param, Post, Put, Res, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse as SwaggerApiResponse, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtPayload } from '../../core/login_core/login_core.service';
import { CurrentUser } from '../../gateway/auth/current_user.decorator';
import { JwtAuthGuard } from '../../gateway/auth/jwt_auth.guard';
import { SaveRoomDecorPlacementDto } from './dto/save_room_decor_placement.dto';
import { RoomDecorService } from './room_decor.service';

@ApiTags('room-decor')
@ApiBearerAuth()
@Controller('rooms')
@UseGuards(JwtAuthGuard)
export class RoomDecorController {
  constructor(private readonly roomDecorService: RoomDecorService) {}

  @ApiOperation({
    summary: '获取房间家具背包和摆放状态',
    description: '返回当前账号已拥有的房间摆件，以及每个摆件的摆放位置。',
  })
  @SwaggerApiResponse({
    status: 200,
    description: '房间家具背包获取成功',
  })
  @Get('me/decor-placements')
  async getInventory(@CurrentUser() user: JwtPayload, @Res() res: Response): Promise<void> {
    const data = await this.roomDecorService.getInventory(BigInt(user.sub));
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '房间家具背包获取成功',
    });
  }

  @ApiOperation({
    summary: '参观其他玩家的房间布局',
    description: '按房主访问策略返回只读布局；拉黑关系始终拒绝访问。',
  })
  @SwaggerApiResponse({ status: 200, description: '只读房间布局获取成功' })
  @Get(':ownerUserId/decor-placements')
  async getRoomView(
    @CurrentUser() user: JwtPayload,
    @Param('ownerUserId') ownerUserId: string,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.roomDecorService.getRoomView(BigInt(user.sub), this.parseUserId(ownerUserId));
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '房间布局获取成功',
    });
  }

  @ApiOperation({
    summary: '收回当前账号所有已摆放家具',
    description: '仅清空布局，不删除已拥有家具资产。',
  })
  @SwaggerApiResponse({ status: 200, description: '房间布局已重置' })
  @Post('me/decor-placements/reset')
  async resetPlacements(@CurrentUser() user: JwtPayload, @Res() res: Response): Promise<void> {
    const data = await this.roomDecorService.resetPlacements(BigInt(user.sub));
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '房间布局已重置，家具已收回背包',
    });
  }

  @ApiOperation({
    summary: '保存房间家具摆放',
    description: '保存当前账号某个家具的摆放状态、位置、缩放和层级。',
  })
  @SwaggerApiResponse({
    status: 200,
    description: '家具摆放保存成功',
  })
  @Put('me/decor-placements/:decorId')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async savePlacement(
    @CurrentUser() user: JwtPayload,
    @Param('decorId') decorId: string,
    @Body() placementDto: SaveRoomDecorPlacementDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.roomDecorService.savePlacement(BigInt(user.sub), {
      ...placementDto,
      decor_id: decorId,
    });
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '家具摆放保存成功',
    });
  }

  private parseUserId(value: string): bigint {
    if (!/^\d+$/.test(value)) {
      throw new BadRequestException('房主用户ID格式不正确');
    }
    return BigInt(value);
  }
}
