/**
 * 转让内部 API 控制器（纯新增）
 * 供 transfer-service 内部调用查询认种订单和持仓数据
 * 不需要 JWT 认证（服务间内部调用）
 *
 * 回滚方式：删除此文件并从 api.module.ts 中移除引用
 */

import {
  Controller,
  Get,
  Param,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';

@ApiTags('内部接口-转让')
@Controller('internal')
export class InternalTransferController {
  private readonly logger = new Logger(InternalTransferController.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 查询认种订单详情（含转让可用信息）
   * 供 transfer-service 在创建转让订单时验证
   */
  @Get('planting-orders/:orderNo')
  @ApiOperation({ summary: '查询认种订单（内部）' })
  async getPlantingOrder(
    @Param('orderNo') orderNo: string,
  ): Promise<{
    id: string;
    orderNo: string;
    userId: string;
    accountSequence: string;
    treeCount: number;
    status: string;
    selectedProvince: string;
    selectedCity: string;
    transferLockedCount: number;
    transferredCount: number;
    availableForTransfer: number;
    miningEnabledAt: string | null;
    createdAt: string;
  }> {
    const order = await this.prisma.plantingOrder.findUnique({
      where: { orderNo },
    });

    if (!order) {
      throw new NotFoundException(`认种订单 ${orderNo} 不存在`);
    }

    // 计算已完成转让的棵数
    const transferredAgg =
      await this.prisma.plantingTransferRecord.aggregate({
        where: { sourceOrderNo: orderNo, status: 'TRANSFERRED' },
        _sum: { treeCount: true },
      });
    const transferredCount = transferredAgg._sum.treeCount || 0;
    const availableForTransfer =
      order.treeCount -
      (order.transferLockedCount || 0) -
      transferredCount;

    return {
      id: order.id.toString(),
      orderNo: order.orderNo,
      userId: order.userId.toString(),
      accountSequence: order.accountSequence,
      treeCount: order.treeCount,
      status: order.status,
      selectedProvince: order.selectedProvince || '',
      selectedCity: order.selectedCity || '',
      transferLockedCount: order.transferLockedCount || 0,
      transferredCount,
      availableForTransfer: Math.max(0, availableForTransfer),
      miningEnabledAt: order.miningEnabledAt?.toISOString() || null,
      createdAt: order.createdAt.toISOString(),
    };
  }

  /**
   * 查询用户持仓
   * 供 transfer-service 查询买卖方持仓信息
   */
  @Get('planting-positions/:userId')
  @ApiOperation({ summary: '查询用户持仓（内部）' })
  async getUserPosition(
    @Param('userId') userId: string,
  ): Promise<{
    userId: string;
    totalTreeCount: number;
    effectiveTreeCount: number;
  }> {
    const position = await this.prisma.plantingPosition.findUnique({
      where: { userId: BigInt(userId) },
    });

    if (!position) {
      throw new NotFoundException(`用户 ${userId} 持仓不存在`);
    }

    return {
      userId: position.userId.toString(),
      totalTreeCount: position.totalTreeCount,
      effectiveTreeCount: position.effectiveTreeCount,
    };
  }

  /**
   * 查询树的原始算力值和日期信息
   * 供 transfer-service 创建转让订单时获取转让标的信息
   */
  @Get('planting-orders/:orderNo/contribution')
  @ApiOperation({ summary: '查询认种订单算力信息（内部）' })
  async getContributionPerTree(
    @Param('orderNo') orderNo: string,
  ): Promise<{
    contributionPerTree: string;
    adoptionDate: string;
    expireDate: string;
  }> {
    const order = await this.prisma.plantingOrder.findUnique({
      where: { orderNo },
    });

    if (!order) {
      throw new NotFoundException(`认种订单 ${orderNo} 不存在`);
    }

    // 每棵树的基础算力值 = 总金额 / 棵数
    const contributionPerTree = order.totalAmount.div(order.treeCount);

    // 认种生效日期（优先使用支付时间）
    const adoptionDate =
      order.paidAt || order.miningEnabledAt || order.createdAt;

    // 到期日期（认种合同期 5 年）
    const expireDate = new Date(adoptionDate);
    expireDate.setFullYear(expireDate.getFullYear() + 5);

    return {
      contributionPerTree: contributionPerTree.toString(),
      adoptionDate: adoptionDate.toISOString(),
      expireDate: expireDate.toISOString(),
    };
  }
}
