import {
  Controller,
  Get,
  Post,
  Param,
  Body,
  Query,
  UseGuards,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { WithdrawalService } from '@/modules/shared/finance/withdrawal.service';
import { SellerJwtAuthGuard } from '@/common/guards/seller-jwt-auth.guard';
import { CurrentSeller } from '@/common/decorators/current-seller.decorator';
import { MerchantService } from '@/modules/merchant/merchant.service';
import {
  CreateMerchantWithdrawalDto,
  QueryMerchantWithdrawalDto,
} from '@/modules/shared/finance/dto/withdrawal.dto';

@ApiTags('提现管理(商家)')
@Controller('merchant/finance/withdrawals')
@UseGuards(SellerJwtAuthGuard)
@ApiBearerAuth()
export class WithdrawalMerchantController {
  constructor(
    private readonly withdrawalService: WithdrawalService,
    private readonly merchantService: MerchantService,
  ) {}

  private async getMerchantId(sellerId: number): Promise<number> {
    const merchant = await this.merchantService.findBySellerId(sellerId);
    if (!merchant) throw new NotFoundException('店铺不存在');
    return merchant.id;
  }

  @Post()
  @ApiOperation({ summary: '商家申请提现' })
  async createWithdrawal(
    @CurrentSeller('sub') sellerId: number,
    @Body() dto: CreateMerchantWithdrawalDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    return this.withdrawalService.createMerchantWithdrawal(merchantId, dto);
  }

  @Get()
  @ApiOperation({ summary: '商家查询提现记录' })
  async getWithdrawals(
    @CurrentSeller('sub') sellerId: number,
    @Query() dto: QueryMerchantWithdrawalDto,
  ) {
    const merchantId = await this.getMerchantId(sellerId);
    return this.withdrawalService.getMerchantWithdrawals({
      merchantId,
      status: dto.status,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: '商家查询提现详情' })
  async getWithdrawalDetail(
    @CurrentSeller('sub') sellerId: number,
    @Param('id') id: number,
  ) {
    // TODO: 实现查询提现详情，需要验证提现记录属于当前商家
    return { message: '功能开发中' };
  }
}
