import {
  Controller,
  Get,
  Post,
  Param,
  Body,
  Logger,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam, ApiResponse } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/database/prisma.service';

/**
 * 内部预种统计API - 供其他微服务调用
 * 无需JWT认证（服务间内部通信）
 */
@ApiTags('Internal Pre-Planting Stats API')
@Controller('internal/referral/pre-planting-stats')
export class InternalPrePlantingStatsController {
  private readonly logger = new Logger(InternalPrePlantingStatsController.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 根据 accountSequence 获取单个用户的预种统计
   */
  @Get(':accountSequence')
  @ApiOperation({ summary: '获取用户预种统计（内部API）' })
  @ApiParam({ name: 'accountSequence', description: '账户序列号 (格式: D + YYMMDD + 5位序号)' })
  @ApiResponse({
    status: 200,
    description: '预种统计数据',
    schema: {
      type: 'object',
      properties: {
        selfPrePlantingPortions: { type: 'number', description: '个人预种份数' },
        teamPrePlantingPortions: { type: 'number', description: '团队预种份数（含自己和所有下级）' },
      },
    },
  })
  async getPrePlantingStats(@Param('accountSequence') accountSequence: string) {
    this.logger.debug(`[INTERNAL] getPrePlantingStats: ${accountSequence}`);

    const relationship = await this.prisma.referralRelationship.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    if (!relationship) {
      this.logger.debug(`[INTERNAL] No referral found for accountSequence: ${accountSequence}`);
      return {
        selfPrePlantingPortions: 0,
        teamPrePlantingPortions: 0,
      };
    }

    const stats = await this.prisma.teamStatistics.findUnique({
      where: { userId: relationship.userId },
      select: {
        selfPrePlantingPortions: true,
        teamPrePlantingPortions: true,
      },
    });

    if (!stats) {
      this.logger.debug(`[INTERNAL] No team statistics found for userId: ${relationship.userId}`);
      return {
        selfPrePlantingPortions: 0,
        teamPrePlantingPortions: 0,
      };
    }

    return {
      selfPrePlantingPortions: stats.selfPrePlantingPortions,
      teamPrePlantingPortions: stats.teamPrePlantingPortions,
    };
  }

  /**
   * 批量获取多个用户的预种统计
   */
  @Post('batch')
  @ApiOperation({ summary: '批量获取用户预种统计（内部API）' })
  @ApiResponse({
    status: 200,
    description: '批量预种统计数据 (Map: accountSequence → stats)',
    schema: {
      type: 'object',
      additionalProperties: {
        type: 'object',
        properties: {
          selfPrePlantingPortions: { type: 'number' },
          teamPrePlantingPortions: { type: 'number' },
        },
      },
    },
  })
  async getBatchPrePlantingStats(
    @Body() body: { accountSequences: string[] },
  ) {
    const { accountSequences } = body;
    this.logger.debug(`[INTERNAL] getBatchPrePlantingStats: ${accountSequences.length} accounts`);

    // 批量查询所有 referral relationships
    const relationships = await this.prisma.referralRelationship.findMany({
      where: { accountSequence: { in: accountSequences } },
      select: { accountSequence: true, userId: true },
    });

    const accountToUserId = new Map<string, bigint>();
    for (const rel of relationships) {
      accountToUserId.set(rel.accountSequence, rel.userId);
    }

    // 批量查询所有 team statistics
    const userIds = relationships.map((r) => r.userId);
    const allStats = await this.prisma.teamStatistics.findMany({
      where: { userId: { in: userIds } },
      select: {
        userId: true,
        selfPrePlantingPortions: true,
        teamPrePlantingPortions: true,
      },
    });

    const userIdToStats = new Map<bigint, { selfPrePlantingPortions: number; teamPrePlantingPortions: number }>();
    for (const s of allStats) {
      userIdToStats.set(s.userId, {
        selfPrePlantingPortions: s.selfPrePlantingPortions,
        teamPrePlantingPortions: s.teamPrePlantingPortions,
      });
    }

    // 组装结果
    const result: Record<string, { selfPrePlantingPortions: number; teamPrePlantingPortions: number }> = {};

    for (const seq of accountSequences) {
      const userId = accountToUserId.get(seq);
      if (userId) {
        const stats = userIdToStats.get(userId);
        result[seq] = stats ?? { selfPrePlantingPortions: 0, teamPrePlantingPortions: 0 };
      } else {
        result[seq] = { selfPrePlantingPortions: 0, teamPrePlantingPortions: 0 };
      }
    }

    return result;
  }
}
