import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Param,
  Body,
  Query,
  UseGuards,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { MerchantRoomService } from './room.service';
import { SellerJwtAuthGuard } from '@/common/guards/seller-jwt-auth.guard';
import { CurrentSeller } from '@/common/decorators/current-seller.decorator';
import { MerchantProfileService } from '../profile/profile.service';
import { CreateRoomDto, UpdateRoomDto, QueryRoomDto } from './dto/room.dto';

@ApiTags('房源管理(商家)')
@Controller('merchant/rooms')
@UseGuards(SellerJwtAuthGuard)
@ApiBearerAuth()
export class MerchantRoomController {
  constructor(
    private readonly roomService: MerchantRoomService,
    private readonly profileService: MerchantProfileService,
  ) {}

  @Get()
  @ApiOperation({ summary: '我的房源列表' })
  async findMine(
    @CurrentSeller('sub') sellerId: number,
    @Query() query: QueryRoomDto,
  ) {
    const merchant = await this.profileService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return this.roomService.findByMerchant(Number(merchant.id), query);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取单个房源详情' })
  async findOne(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
  ) {
    const merchant = await this.profileService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return this.roomService.findByIdAndMerchant(
      Number(id),
      Number(merchant.id),
    );
  }

  @Post()
  @ApiOperation({ summary: '添加房源' })
  async create(
    @CurrentSeller('sub') sellerId: number,
    @Body() dto: CreateRoomDto,
  ) {
    const merchant = await this.profileService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return this.roomService.create(Number(merchant.id), dto);
  }

  @Put(':id')
  @ApiOperation({ summary: '更新房源' })
  async update(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
    @Body() dto: UpdateRoomDto,
  ) {
    const merchant = await this.profileService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return this.roomService.update(Number(id), Number(merchant.id), dto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '下架房源' })
  async remove(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
  ) {
    const merchant = await this.profileService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return this.roomService.remove(Number(id), Number(merchant.id));
  }
}
