import {
  Controller,
  Get,
  Post,
  Param,
  Query,
  NotFoundException,
} from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { TransferApplicationService } from '../../application/services/transfer-application.service';
import { TransferOrderResponse } from '../dto/response/transfer-order.response';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';

@ApiTags('管理端')
@Controller('admin/transfers')
export class AdminTransferController {
  constructor(
    private readonly transferService: TransferApplicationService,
    private readonly prisma: PrismaService,
  ) {}

  @Get()
  @ApiOperation({ summary: '转让列表（管理端）' })
  async listTransfers(
    @Query('status') status?: string,
    @Query('limit') limit: number = 20,
    @Query('offset') offset: number = 0,
  ): Promise<{ total: number; items: any[] }> {
    const where = status ? { status } : {};

    const [total, items] = await Promise.all([
      this.prisma.transferOrder.count({ where }),
      this.prisma.transferOrder.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        take: limit,
        skip: offset,
      }),
    ]);

    return {
      total,
      items: items.map((item) => ({
        ...item,
        id: item.id.toString(),
        sellerUserId: item.sellerUserId.toString(),
        buyerUserId: item.buyerUserId.toString(),
        sourceAdoptionId: item.sourceAdoptionId.toString(),
        contributionPerTree: item.contributionPerTree.toString(),
        transferPrice: item.transferPrice.toString(),
        platformFeeAmount: item.platformFeeAmount.toString(),
        sellerReceiveAmount: item.sellerReceiveAmount.toString(),
      })),
    };
  }

  @Get('stats')
  @ApiOperation({ summary: '转让统计' })
  async getStats(): Promise<any> {
    const [total, pending, completed, cancelled, failed] = await Promise.all([
      this.prisma.transferOrder.count(),
      this.prisma.transferOrder.count({ where: { status: 'PENDING' } }),
      this.prisma.transferOrder.count({ where: { status: 'COMPLETED' } }),
      this.prisma.transferOrder.count({ where: { status: 'CANCELLED' } }),
      this.prisma.transferOrder.count({ where: { status: { in: ['FAILED', 'ROLLED_BACK'] } } }),
    ]);

    return { total, pending, completed, cancelled, failed };
  }

  @Get(':transferOrderNo')
  @ApiOperation({ summary: '转让详情（管理端）' })
  async getTransferDetail(
    @Param('transferOrderNo') transferOrderNo: string,
  ): Promise<any> {
    const order = await this.prisma.transferOrder.findUnique({
      where: { transferOrderNo },
      include: { statusLogs: { orderBy: { createdAt: 'asc' } } },
    });

    if (!order) {
      throw new NotFoundException(`转让订单 ${transferOrderNo} 不存在`);
    }

    return {
      ...order,
      id: order.id.toString(),
      sellerUserId: order.sellerUserId.toString(),
      buyerUserId: order.buyerUserId.toString(),
      sourceAdoptionId: order.sourceAdoptionId.toString(),
      contributionPerTree: order.contributionPerTree.toString(),
      transferPrice: order.transferPrice.toString(),
      platformFeeAmount: order.platformFeeAmount.toString(),
      sellerReceiveAmount: order.sellerReceiveAmount.toString(),
      statusLogs: order.statusLogs.map((log) => ({
        ...log,
        id: log.id.toString(),
      })),
    };
  }

  @Post(':transferOrderNo/force-cancel')
  @ApiOperation({ summary: '强制取消转让（管理端）' })
  async forceCancel(
    @Param('transferOrderNo') transferOrderNo: string,
  ): Promise<{ success: boolean }> {
    // 管理员强制取消，用系统用户ID
    await this.transferService.cancelTransfer(
      transferOrderNo,
      BigInt(0), // 系统操作，需在 cancelTransfer 中增加管理员权限判断
    );
    return { success: true };
  }
}
