import {
  Controller,
  Post,
  Get,
  Body,
  Param,
  Res,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
  StreamableFile,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { Response } from 'express';
import { PrePlantingApplicationService } from '../../application/services/pre-planting-application.service';
import { PrePlantingRewardEntryRepository } from '../../infrastructure/repositories/pre-planting-reward-entry.repository';
import { PurchasePrePlantingDto } from '../dto/request/purchase-pre-planting.dto';
import { SignPrePlantingContractDto } from '../dto/request/sign-pre-planting-contract.dto';
import { JwtAuthGuard } from '../../../api/guards/jwt-auth.guard';

interface AuthenticatedRequest {
  user: { id: string; accountSequence: string };
}

@ApiTags('预种计划')
@ApiBearerAuth()
@Controller('pre-planting')
@UseGuards(JwtAuthGuard)
export class PrePlantingController {
  constructor(
    private readonly prePlantingService: PrePlantingApplicationService,
    private readonly rewardEntryRepo: PrePlantingRewardEntryRepository,
  ) {}

  @Post('purchase')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '购买预种份额' })
  @ApiResponse({ status: HttpStatus.CREATED, description: '购买成功' })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '参数错误或校验失败' })
  async purchase(
    @Req() req: AuthenticatedRequest,
    @Body() dto: PurchasePrePlantingDto,
  ) {
    const userId = BigInt(req.user.id);
    const accountSequence = req.user.accountSequence;
    return this.prePlantingService.purchasePortion(
      userId,
      accountSequence,
      dto.portionCount,
      dto.provinceCode,
      dto.cityCode,
      dto.provinceName,
      dto.cityName,
    );
  }

  @Post('sign-contract')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '签署合并后的合同' })
  @ApiResponse({ status: HttpStatus.OK, description: '签署成功' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '合并记录不存在' })
  async signContract(
    @Req() req: AuthenticatedRequest,
    @Body() dto: SignPrePlantingContractDto,
  ) {
    const userId = BigInt(req.user.id);
    await this.prePlantingService.signContract(userId, dto.mergeNo);
    return { success: true };
  }

  @Get('eligibility')
  @ApiOperation({ summary: '查询当前用户预种购买资格' })
  @ApiResponse({ status: HttpStatus.OK, description: '资格信息' })
  async getEligibility(@Req() req: AuthenticatedRequest) {
    return this.prePlantingService.getEligibility(req.user.accountSequence);
  }

  @Get('position')
  @ApiOperation({ summary: '获取预种持仓信息' })
  @ApiResponse({ status: HttpStatus.OK, description: '持仓信息' })
  async getPosition(@Req() req: AuthenticatedRequest) {
    const userId = BigInt(req.user.id);
    return this.prePlantingService.getPosition(userId);
  }

  @Get('orders')
  @ApiOperation({ summary: '获取预种订单列表' })
  @ApiResponse({ status: HttpStatus.OK, description: '订单列表' })
  async getOrders(@Req() req: AuthenticatedRequest) {
    const userId = BigInt(req.user.id);
    return this.prePlantingService.getOrders(userId);
  }

  @Get('merges')
  @ApiOperation({ summary: '获取合并记录列表' })
  @ApiResponse({ status: HttpStatus.OK, description: '合并记录列表' })
  async getMerges(@Req() req: AuthenticatedRequest) {
    const userId = BigInt(req.user.id);
    return this.prePlantingService.getMerges(userId);
  }

  /**
   * 获取"我收到的"预种奖励（作为收款方）
   * 返回格式与 reward-service 的 summary + settleable 对齐，方便前端合并
   */
  @Get('my-rewards')
  @ApiOperation({ summary: '获取我收到的预种奖励' })
  @ApiResponse({ status: HttpStatus.OK, description: '预种奖励汇总+明细' })
  async getMyRewards(@Req() req: AuthenticatedRequest) {
    const accountSequence = req.user.accountSequence;
    const entries = await this.rewardEntryRepo.findByRecipientAccountSequence(accountSequence);

    // 只返回用户账户收到的奖励（D 开头），排除系统账户
    const userEntries = entries.filter(e => e.recipientAccountSequence.startsWith('D'));

    // settleableUsdt 设为 0：预种奖励的可结算状态由 wallet-service 管理，
    // wallet-service 的 getSettleableRewards / getMyRewardSummary 已包含预种的可结算部分。
    // pre_planting_reward_entries 只是分配记录，不反映实际的 PENDING/SETTLEABLE 状态。
    // 之前错误地把所有分配记录的金额算作 settleableUsdt，导致前端重复计算。

    return {
      summary: {
        settleableUsdt: 0,
      },
      settleableRewards: userEntries.map(e => ({
        id: `pp-${e.sourceOrderNo}-${e.rightType}`,
        rightType: e.rightType,
        usdtAmount: e.usdtAmount,
        hashpowerAmount: 0,
        createdAt: e.createdAt.toISOString(),
        claimedAt: null,
        sourceOrderNo: e.sourceOrderNo,
        sourceAccountSequence: e.sourceAccountSequence,
        memo: e.memo || '',
      })),
    };
  }

  @Get('merges/:mergeNo/contract-pdf')
  @ApiOperation({ summary: '下载合并合同预览 PDF' })
  @ApiResponse({ status: HttpStatus.OK, description: 'PDF 文件' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '合并记录不存在' })
  async getMergeContractPdf(
    @Req() req: AuthenticatedRequest,
    @Param('mergeNo') mergeNo: string,
    @Res({ passthrough: true }) res: Response,
  ): Promise<StreamableFile> {
    const userId = BigInt(req.user.id);
    const pdfBuffer = await this.prePlantingService.getMergeContractPdf(userId, mergeNo);
    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': `inline; filename="merge-contract-${mergeNo}.pdf"`,
      'Content-Length': pdfBuffer.length,
    });
    return new StreamableFile(pdfBuffer);
  }

  @Get('merges/:mergeNo')
  @ApiOperation({ summary: '获取单条合并记录详情' })
  @ApiResponse({ status: HttpStatus.OK, description: '合并记录详情' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '合并记录不存在' })
  async getMergeDetail(
    @Req() req: AuthenticatedRequest,
    @Param('mergeNo') mergeNo: string,
  ) {
    const userId = BigInt(req.user.id);
    return this.prePlantingService.getMergeDetail(userId, mergeNo);
  }
}
