import {
  Controller,
  Get,
  Query,
  UseGuards,
  Logger,
  ParseIntPipe,
  DefaultValuePipe,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiQuery,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../guards';
import { CurrentUser } from '../decorators';
import { PrismaService } from '../../infrastructure/database/prisma.service';

/**
 * 团队预种统计 — 公开 API（JWT 认证）
 *
 * [功能6] App 端查看团队预种数量：
 * - 所有用户：可看到自己的预种份数、团队预种总量、直推成员预种份数
 * - 市/省公司用户：额外可看到全部团队成员的预种明细（分页）
 *
 * 纯新增控制器，不修改任何现有业务逻辑。
 */
@ApiTags('Team Pre-Planting')
@Controller('referral')
export class TeamPrePlantingController {
  private readonly logger = new Logger(TeamPrePlantingController.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取当前用户的团队预种统计（含直推明细）
   *
   * 所有已登录用户均可调用。
   */
  @Get('me/team-pre-planting')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取团队预种统计（含直推明细）' })
  @ApiResponse({
    status: 200,
    description: '团队预种统计',
    schema: {
      type: 'object',
      properties: {
        selfPrePlantingPortions: { type: 'number', description: '个人预种份数' },
        teamPrePlantingPortions: { type: 'number', description: '团队预种总量（不含自己，仅伞下成员）' },
        directReferrals: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              accountSequence: { type: 'string' },
              selfPrePlantingPortions: { type: 'number' },
            },
          },
        },
      },
    },
  })
  async getTeamPrePlanting(
    @CurrentUser('accountSequence') accountSequence: string,
  ) {
    this.logger.log(`[getTeamPrePlanting] accountSequence=${accountSequence}`);

    // 1. 查当前用户的 referral relationship
    const relationship = await this.prisma.referralRelationship.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    if (!relationship) {
      return {
        selfPrePlantingPortions: 0,
        teamPrePlantingPortions: 0,
        directReferrals: [],
      };
    }

    const userId = relationship.userId;

    // 2. 查当前用户的 TeamStatistics
    const myStats = await this.prisma.teamStatistics.findUnique({
      where: { userId },
      select: {
        selfPrePlantingPortions: true,
        teamPrePlantingPortions: true,
      },
    });

    // 3. 查直推列表
    const directReferrals = await this.prisma.referralRelationship.findMany({
      where: { referrerId: userId },
      select: { userId: true, accountSequence: true },
    });

    // 4. 批量查直推的 TeamStatistics
    let directReferralStats: Array<{ accountSequence: string; selfPrePlantingPortions: number }> = [];
    if (directReferrals.length > 0) {
      const directUserIds = directReferrals.map((r) => r.userId);
      const directTeamStats = await this.prisma.teamStatistics.findMany({
        where: { userId: { in: directUserIds } },
        select: { userId: true, selfPrePlantingPortions: true },
      });

      const userIdToPortions = new Map<bigint, number>();
      for (const s of directTeamStats) {
        userIdToPortions.set(s.userId, s.selfPrePlantingPortions);
      }

      directReferralStats = directReferrals.map((r) => ({
        accountSequence: r.accountSequence,
        selfPrePlantingPortions: userIdToPortions.get(r.userId) ?? 0,
      }));

      // 按预种份数降序排列
      directReferralStats.sort((a, b) => b.selfPrePlantingPortions - a.selfPrePlantingPortions);
    }

    const selfPortions = myStats?.selfPrePlantingPortions ?? 0;
    const teamPortions = myStats?.teamPrePlantingPortions ?? 0;

    return {
      selfPrePlantingPortions: selfPortions,
      // 团队预种量不含自己，只统计伞下成员
      teamPrePlantingPortions: teamPortions - selfPortions,
      directReferrals: directReferralStats,
    };
  }

  /**
   * 获取全部团队成员的预种明细（分页）
   *
   * 面向市公司/省公司管理者使用，前端根据角色控制是否展示。
   * 后端不做角色校验（数据本身不涉密），仅返回有预种份数的团队成员。
   */
  @Get('me/team-pre-planting/members')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取团队成员预种明细（分页）' })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: '每页数量 (默认20, 最大100)' })
  @ApiQuery({ name: 'offset', required: false, type: Number, description: '偏移量 (默认0)' })
  @ApiResponse({
    status: 200,
    description: '团队成员预种明细',
    schema: {
      type: 'object',
      properties: {
        members: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              accountSequence: { type: 'string' },
              selfPrePlantingPortions: { type: 'number' },
            },
          },
        },
        total: { type: 'number' },
        hasMore: { type: 'boolean' },
      },
    },
  })
  async getTeamPrePlantingMembers(
    @CurrentUser('accountSequence') accountSequence: string,
    @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number,
    @Query('offset', new DefaultValuePipe(0), ParseIntPipe) offset: number,
  ) {
    this.logger.log(`[getTeamPrePlantingMembers] accountSequence=${accountSequence}, limit=${limit}, offset=${offset}`);

    // 限制 limit 范围
    const safeLimit = Math.min(Math.max(limit, 1), 100);

    // 1. 查当前用户的 userId
    const relationship = await this.prisma.referralRelationship.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    if (!relationship) {
      return { members: [], total: 0, hasMore: false };
    }

    const userId = relationship.userId;

    // 2. 用原生 SQL 查 ancestor_path 包含当前 userId 的所有下级
    //    JOIN team_statistics 获取预种份数，只返回 > 0 的
    const countResult = await this.prisma.$queryRaw<[{ count: bigint }]>`
      SELECT COUNT(*) as count
      FROM referral_relationships rr
      JOIN team_statistics ts ON rr.user_id = ts.user_id
      WHERE ${userId} = ANY(rr.ancestor_path)
        AND ts.self_pre_planting_portions > 0
    `;

    const total = Number(countResult[0]?.count ?? 0);

    if (total === 0) {
      return { members: [], total: 0, hasMore: false };
    }

    const members = await this.prisma.$queryRaw<
      Array<{ account_sequence: string; self_pre_planting_portions: number }>
    >`
      SELECT rr.account_sequence, ts.self_pre_planting_portions
      FROM referral_relationships rr
      JOIN team_statistics ts ON rr.user_id = ts.user_id
      WHERE ${userId} = ANY(rr.ancestor_path)
        AND ts.self_pre_planting_portions > 0
      ORDER BY ts.self_pre_planting_portions DESC
      LIMIT ${safeLimit} OFFSET ${offset}
    `;

    return {
      members: members.map((m) => ({
        accountSequence: m.account_sequence,
        selfPrePlantingPortions: m.self_pre_planting_portions,
      })),
      total,
      hasMore: offset + safeLimit < total,
    };
  }
}
