import {
  Controller,
  Get,
  Post,
  Param,
  Query,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiParam,
  ApiQuery,
} from '@nestjs/swagger';
import { PrePlantingApplicationService } from '../../application/services/pre-planting-application.service';
import { PrismaService } from '../../../infrastructure/persistence/prisma/prisma.service';

@ApiTags('预种计划-内部API')
@Controller('internal/pre-planting')
export class InternalPrePlantingController {
  private readonly logger = new Logger(InternalPrePlantingController.name);

  constructor(
    private readonly prePlantingService: PrePlantingApplicationService,
    private readonly prisma: PrismaService,
  ) {}

  @Get('eligibility/:accountSequence')
  @ApiOperation({ summary: '查询预种资格信息（内部API）' })
  @ApiParam({ name: 'accountSequence', description: '用户账户序列号' })
  @ApiResponse({ status: HttpStatus.OK, description: '资格信息' })
  async getEligibility(
    @Param('accountSequence') accountSequence: string,
  ) {
    return this.prePlantingService.getEligibility(accountSequence);
  }

  // ============================================
  // [2026-02-27] 新增：管理员查询端点（供 admin-service 内部调用）
  // ============================================

  @Get('admin/orders')
  @ApiOperation({ summary: '预种订单列表（管理员视角）' })
  @ApiQuery({ name: 'page', required: false })
  @ApiQuery({ name: 'pageSize', required: false })
  @ApiQuery({ name: 'keyword', required: false })
  @ApiQuery({ name: 'status', required: false })
  @ApiQuery({ name: 'accountSequences', required: false, description: '逗号分隔的 accountSequence 列表，用于团队筛选' })
  async getAdminOrders(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
    @Query('status') status?: string,
    @Query('accountSequences') accountSequences?: string,
  ) {
    const p = Math.max(1, parseInt(page || '1', 10));
    const ps = Math.min(100, Math.max(1, parseInt(pageSize || '20', 10)));

    const where: any = {};
    if (status) where.status = status;
    if (accountSequences) {
      const seqList = accountSequences.split(',').map((s) => s.trim()).filter(Boolean);
      if (seqList.length > 0) {
        where.accountSequence = { in: seqList };
      }
    }
    if (keyword) {
      // 当同时存在 accountSequences 时，keyword 只搜 orderNo（accountSequence 已被限定）
      if (accountSequences) {
        where.OR = [
          { orderNo: { contains: keyword, mode: 'insensitive' } },
        ];
      } else {
        where.OR = [
          { orderNo: { contains: keyword, mode: 'insensitive' } },
          { accountSequence: { contains: keyword, mode: 'insensitive' } },
        ];
      }
    }

    const [items, total] = await Promise.all([
      this.prisma.prePlantingOrder.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (p - 1) * ps,
        take: ps,
      }),
      this.prisma.prePlantingOrder.count({ where }),
    ]);

    return {
      items: items.map((o) => ({
        id: o.id.toString(),
        orderNo: o.orderNo,
        userId: o.userId.toString(),
        accountSequence: o.accountSequence,
        portionCount: o.portionCount,
        pricePerPortion: Number(o.pricePerPortion),
        totalAmount: Number(o.totalAmount),
        provinceCode: o.provinceCode,
        cityCode: o.cityCode,
        status: o.status,
        mergedToMergeId: o.mergedToMergeId?.toString() ?? null,
        createdAt: o.createdAt.toISOString(),
        paidAt: o.paidAt?.toISOString() ?? null,
        mergedAt: o.mergedAt?.toISOString() ?? null,
      })),
      total,
      page: p,
      pageSize: ps,
    };
  }

  @Get('admin/positions')
  @ApiOperation({ summary: '预种持仓列表（管理员视角）' })
  @ApiQuery({ name: 'page', required: false })
  @ApiQuery({ name: 'pageSize', required: false })
  @ApiQuery({ name: 'keyword', required: false })
  @ApiQuery({ name: 'accountSequences', required: false, description: '逗号分隔的 accountSequence 列表，用于团队筛选' })
  async getAdminPositions(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
    @Query('accountSequences') accountSequences?: string,
  ) {
    const p = Math.max(1, parseInt(page || '1', 10));
    const ps = Math.min(100, Math.max(1, parseInt(pageSize || '20', 10)));

    const where: any = {};
    if (accountSequences) {
      const seqList = accountSequences.split(',').map((s) => s.trim()).filter(Boolean);
      if (seqList.length > 0) {
        where.accountSequence = { in: seqList };
      }
    }
    if (keyword) {
      // 当同时存在 accountSequences 时，用 AND 组合两个条件
      if (accountSequences && where.accountSequence) {
        where.AND = [
          { accountSequence: where.accountSequence },
          { accountSequence: { contains: keyword, mode: 'insensitive' } },
        ];
        delete where.accountSequence;
      } else {
        where.accountSequence = { contains: keyword, mode: 'insensitive' };
      }
    }

    const [items, total] = await Promise.all([
      this.prisma.prePlantingPosition.findMany({
        where,
        orderBy: { updatedAt: 'desc' },
        skip: (p - 1) * ps,
        take: ps,
      }),
      this.prisma.prePlantingPosition.count({ where }),
    ]);

    return {
      items: items.map((pos) => ({
        id: pos.id.toString(),
        userId: pos.userId.toString(),
        accountSequence: pos.accountSequence,
        totalPortions: pos.totalPortions,
        availablePortions: pos.availablePortions,
        mergedPortions: pos.mergedPortions,
        totalTreesMerged: pos.totalTreesMerged,
        provinceCode: pos.provinceCode ?? null,
        cityCode: pos.cityCode ?? null,
        firstPurchaseAt: pos.firstPurchaseAt?.toISOString() ?? null,
        updatedAt: pos.updatedAt.toISOString(),
      })),
      total,
      page: p,
      pageSize: ps,
    };
  }

  @Get('admin/merges')
  @ApiOperation({ summary: '预种合并记录列表（管理员视角）' })
  @ApiQuery({ name: 'page', required: false })
  @ApiQuery({ name: 'pageSize', required: false })
  @ApiQuery({ name: 'keyword', required: false })
  @ApiQuery({ name: 'status', required: false })
  async getAdminMerges(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
    @Query('status') status?: string,
  ) {
    const p = Math.max(1, parseInt(page || '1', 10));
    const ps = Math.min(100, Math.max(1, parseInt(pageSize || '20', 10)));

    const where: any = {};
    if (status) where.contractStatus = status;
    if (keyword) {
      where.OR = [
        { mergeNo: { contains: keyword, mode: 'insensitive' } },
        { accountSequence: { contains: keyword, mode: 'insensitive' } },
      ];
    }

    const [items, total] = await Promise.all([
      this.prisma.prePlantingMerge.findMany({
        where,
        orderBy: { mergedAt: 'desc' },
        skip: (p - 1) * ps,
        take: ps,
      }),
      this.prisma.prePlantingMerge.count({ where }),
    ]);

    return {
      items: items.map((m) => ({
        id: m.id.toString(),
        mergeNo: m.mergeNo,
        userId: m.userId.toString(),
        accountSequence: m.accountSequence,
        sourceOrderNos: m.sourceOrderNos as string[],
        treeCount: m.treeCount,
        contractStatus: m.contractStatus,
        contractSignedAt: m.contractSignedAt?.toISOString() ?? null,
        miningEnabledAt: m.miningEnabledAt?.toISOString() ?? null,
        selectedProvince: m.provinceCode ?? null,
        selectedCity: m.cityCode ?? null,
        mergedAt: m.mergedAt.toISOString(),
      })),
      total,
      page: p,
      pageSize: ps,
    };
  }

  @Get('admin/stats')
  @ApiOperation({ summary: '预种统计汇总（管理员视角）' })
  async getAdminStats() {
    const [
      totalOrders,
      portionsAgg,
      amountAgg,
      totalMerges,
      treesMergedAgg,
      totalUsers,
      pendingContracts,
      pendingPortionsAgg,
    ] = await Promise.all([
      this.prisma.prePlantingOrder.count(),
      this.prisma.prePlantingOrder.aggregate({ _sum: { portionCount: true } }),
      this.prisma.prePlantingOrder.aggregate({
        _sum: { totalAmount: true },
        where: { status: { in: ['PAID', 'MERGED'] } },
      }),
      this.prisma.prePlantingMerge.count(),
      this.prisma.prePlantingMerge.aggregate({ _sum: { treeCount: true } }),
      this.prisma.prePlantingPosition.count(),
      this.prisma.prePlantingMerge.count({ where: { contractStatus: 'PENDING' } }),
      this.prisma.prePlantingPosition.aggregate({ _sum: { availablePortions: true } }),
    ]);

    return {
      totalOrders,
      totalPortions: portionsAgg._sum.portionCount ?? 0,
      totalAmount: Number(amountAgg._sum.totalAmount ?? 0),
      totalMerges,
      totalTreesMerged: treesMergedAgg._sum.treeCount ?? 0,
      totalUsers,
      pendingContracts,
      pendingMergePortions: pendingPortionsAgg._sum.availablePortions ?? 0,
    };
  }

}
