import { Controller, Get, Post, Body, Query, Param, Req, Headers, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery, ApiParam } from '@nestjs/swagger';
import { IsString, IsOptional, Length, Matches } from 'class-validator';
import { P2pTransferService } from '../../application/services/p2p-transfer.service';
import { RequireCapability } from '../../shared/decorators/require-capability.decorator';
import { Public } from '../../shared/guards/jwt-auth.guard';

class P2pTransferDto {
  @IsString()
  @Length(11, 11)
  @Matches(/^\d{11}$/, { message: '请输入有效的11位手机号' })
  toPhone: string;

  @IsString()
  amount: string;

  @IsOptional()
  @IsString()
  @Length(0, 100)
  memo?: string;
}

@ApiTags('P2P Transfer')
@ApiBearerAuth()
@Controller('p2p')
export class P2pTransferController {
  constructor(private readonly p2pTransferService: P2pTransferService) {}

  @Get('transfer-fee-config')
  @ApiOperation({ summary: '获取P2P转账手续费配置' })
  async getTransferFeeConfig() {
    return this.p2pTransferService.getP2pFeeConfigPublic();
  }

  @Post('transfer')
  @RequireCapability('P2P_SEND')
  @ApiOperation({ summary: 'P2P转账（积分值）' })
  async transfer(
    @Body() dto: P2pTransferDto,
    @Headers('authorization') authHeader: string,
    @Req() req: any,
  ) {
    const accountSequence = req.user?.accountSequence;
    if (!accountSequence) {
      throw new BadRequestException('Unauthorized');
    }

    const token = authHeader?.replace('Bearer ', '') || '';
    const result = await this.p2pTransferService.transfer(
      accountSequence,
      dto.toPhone,
      dto.amount,
      dto.memo,
      token,
    );

    // TransformInterceptor 会自动包装成 { success: true, data: ... }
    return result;
  }

  @Get('transfers/:accountSequence')
  @RequireCapability('VIEW_RECORDS')
  @ApiOperation({ summary: '获取P2P转账历史' })
  @ApiParam({ name: 'accountSequence', required: true, description: '账户序列号' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getHistory(
    @Param('accountSequence') accountSequence: string,
    @Req() req: any,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    // 验证只能查询自己的转账历史
    const currentUser = req.user?.accountSequence;
    if (!currentUser || currentUser !== accountSequence) {
      throw new BadRequestException('Unauthorized');
    }

    const result = await this.p2pTransferService.getTransferHistory(
      accountSequence,
      page ?? 1,
      pageSize ?? 20,
    );

    // TransformInterceptor 会自动包装成 { success: true, data: ... }
    return result.data;
  }

  @Get('internal/all-transfers')
  @Public()
  @ApiOperation({ summary: '获取全部P2P转账记录（内部调用，管理后台用）' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  @ApiQuery({ name: 'search', required: false, type: String })
  async getAllTransfers(
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
    @Query('search') search?: string,
  ) {
    return this.p2pTransferService.getAllTransfers(
      page ?? 1,
      pageSize ?? 20,
      search,
    );
  }
}
