import { Controller, Get, Post, Param, Query, Body, Req, UnauthorizedException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { TransferService } from '../../application/services/transfer.service';
import { RequireCapability } from '../../shared/decorators/require-capability.decorator';

class TransferDto {
  @IsString()
  amount: string;
}

@ApiTags('Transfer')
@ApiBearerAuth()
@Controller('transfers')
export class TransferController {
  constructor(private readonly transferService: TransferService) {}

  @Post('in')
  @RequireCapability('TRANSFER_IN')
  @ApiOperation({ summary: '从挖矿账户划入积分股' })
  async transferIn(@Body() dto: TransferDto, @Req() req: any) {
    const accountSequence = req.user?.accountSequence;
    if (!accountSequence) {
      throw new UnauthorizedException('未登录');
    }

    return this.transferService.transferIn(accountSequence, dto.amount);
  }

  @Post('out')
  @RequireCapability('TRANSFER_OUT')
  @ApiOperation({ summary: '划出积分股到挖矿账户' })
  async transferOut(@Body() dto: TransferDto, @Req() req: any) {
    const accountSequence = req.user?.accountSequence;
    if (!accountSequence) {
      throw new UnauthorizedException('未登录');
    }

    return this.transferService.transferOut(accountSequence, dto.amount);
  }

  @Get('history')
  @RequireCapability('VIEW_RECORDS')
  @ApiOperation({ summary: '获取划转历史' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getHistory(
    @Req() req: any,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    const accountSequence = req.user?.accountSequence;
    if (!accountSequence) {
      throw new UnauthorizedException('未登录');
    }

    return this.transferService.getTransferHistory(accountSequence, page ?? 1, pageSize ?? 50);
  }
}
