import { Controller, Get, Query, Logger } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { AuthorizationApplicationService, SystemAccountApplicationService } from '@/application/services'

/**
 * 内部授权 API - 供其他微服务调用
 * 无需 JWT 认证（服务间内部通信）
 */
@ApiTags('Internal Authorization API')
@Controller('authorization')
export class InternalAuthorizationController {
  private readonly logger = new Logger(InternalAuthorizationController.name)

  constructor(
    private readonly applicationService: AuthorizationApplicationService,
    // [2026-01-04] 新增：用于系统账户报表统计
    private readonly systemAccountService: SystemAccountApplicationService,
  ) {}

  /**
   * 查找用户推荐链中最近的社区授权用户
   * 用于 reward-service 分配社区权益
   */
  @Get('nearest-community')
  @ApiOperation({ summary: '查找最近的社区授权用户（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '用户的 accountSequence' })
  @ApiResponse({
    status: 200,
    description: '返回最近社区授权用户的 accountSequence，如果没有则返回 null',
    schema: {
      type: 'object',
      properties: {
        accountSequence: { type: 'string', nullable: true },
      },
    },
  })
  async findNearestCommunity(
    @Query('accountSequence') accountSequence: string,
  ): Promise<{ accountSequence: string | null }> {
    this.logger.debug(`[INTERNAL] findNearestCommunity: accountSequence=${accountSequence}`)

    const result = await this.applicationService.findNearestAuthorizedCommunity(
      accountSequence,
    )

    return {
      accountSequence: result,
    }
  }

  /**
   * 查找用户推荐链中最近的省公司授权用户（匹配指定省份）
   * 用于 reward-service 分配省团队权益
   */
  @Get('nearest-province')
  @ApiOperation({ summary: '查找最近的省公司授权用户（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '用户的 accountSequence' })
  @ApiQuery({ name: 'provinceCode', description: '省份代码' })
  @ApiResponse({
    status: 200,
    description: '返回最近省公司授权用户的 accountSequence，如果没有则返回 null',
    schema: {
      type: 'object',
      properties: {
        accountSequence: { type: 'string', nullable: true },
      },
    },
  })
  async findNearestProvince(
    @Query('accountSequence') accountSequence: string,
    @Query('provinceCode') provinceCode: string,
  ): Promise<{ accountSequence: string | null }> {
    this.logger.debug(
      `[INTERNAL] findNearestProvince: accountSequence=${accountSequence}, provinceCode=${provinceCode}`,
    )

    const result = await this.applicationService.findNearestAuthorizedProvince(
      accountSequence,
      provinceCode,
    )

    return {
      accountSequence: result ? result : null,
    }
  }

  /**
   * 查找用户推荐链中最近的市公司授权用户（匹配指定城市）
   * 用于 reward-service 分配市团队权益
   */
  @Get('nearest-city')
  @ApiOperation({ summary: '查找最近的市公司授权用户（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '用户的 accountSequence' })
  @ApiQuery({ name: 'cityCode', description: '城市代码' })
  @ApiResponse({
    status: 200,
    description: '返回最近市公司授权用户的 accountSequence，如果没有则返回 null',
    schema: {
      type: 'object',
      properties: {
        accountSequence: { type: 'string', nullable: true },
      },
    },
  })
  async findNearestCity(
    @Query('accountSequence') accountSequence: string,
    @Query('cityCode') cityCode: string,
  ): Promise<{ accountSequence: string | null }> {
    this.logger.debug(
      `[INTERNAL] findNearestCity: accountSequence=${accountSequence}, cityCode=${cityCode}`,
    )

    const result = await this.applicationService.findNearestAuthorizedCity(
      accountSequence,
      cityCode,
    )

    return {
      accountSequence: result ? result : null,
    }
  }

  /**
   * 获取社区权益分配方案
   * 根据考核规则计算每棵树的社区权益应该分配给谁
   * 用于 reward-service 分配社区权益
   */
  @Get('community-reward-distribution')
  @ApiOperation({ summary: '获取社区权益分配方案（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '认种用户的 accountSequence' })
  @ApiQuery({ name: 'treeCount', description: '认种棵数' })
  @ApiResponse({
    status: 200,
    description: '返回社区权益分配方案',
    schema: {
      type: 'object',
      properties: {
        distributions: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              accountSequence: { type: 'string', description: '接收者账号' },
              treeCount: { type: 'string', description: '分配棵数' },
              reason: { type: 'string', description: '分配原因' },
            },
          },
        },
      },
    },
  })
  async getCommunityRewardDistribution(
    @Query('accountSequence') accountSequence: string,
    @Query('treeCount') treeCount: string,
  ): Promise<{
    distributions: Array<{
      accountSequence: string
      treeCount: number
      reason: string
    }>
  }> {
    this.logger.debug(
      `[INTERNAL] getCommunityRewardDistribution: accountSequence=${accountSequence}, treeCount=${treeCount}`,
    )

    return this.applicationService.getCommunityRewardDistribution(
      accountSequence,
      Number(treeCount),
    )
  }

  /**
   * 获取省团队权益分配方案 (20 USDT)
   */
  @Get('province-team-reward-distribution')
  @ApiOperation({ summary: '获取省团队权益分配方案（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '认种用户的 accountSequence' })
  @ApiQuery({ name: 'provinceCode', description: '省份代码' })
  @ApiQuery({ name: 'treeCount', description: '认种棵数' })
  async getProvinceTeamRewardDistribution(
    @Query('accountSequence') accountSequence: string,
    @Query('provinceCode') provinceCode: string,
    @Query('treeCount') treeCount: string,
  ): Promise<{
    distributions: Array<{
      accountSequence: string
      treeCount: number
      reason: string
    }>
  }> {
    this.logger.debug(
      `[INTERNAL] getProvinceTeamRewardDistribution: accountSequence=${accountSequence}, provinceCode=${provinceCode}, treeCount=${treeCount}`,
    )

    return this.applicationService.getProvinceTeamRewardDistribution(
      accountSequence,
      provinceCode,
      Number(treeCount),
    )
  }

  /**
   * 获取省区域权益分配方案 (15 USDT + 1%算力)
   */
  @Get('province-area-reward-distribution')
  @ApiOperation({ summary: '获取省区域权益分配方案（内部 API）' })
  @ApiQuery({ name: 'provinceCode', description: '省份代码' })
  @ApiQuery({ name: 'treeCount', description: '认种棵数' })
  async getProvinceAreaRewardDistribution(
    @Query('provinceCode') provinceCode: string,
    @Query('treeCount') treeCount: string,
  ): Promise<{
    distributions: Array<{
      accountSequence: string
      treeCount: number
      reason: string
      isSystemAccount: boolean
    }>
  }> {
    this.logger.debug(
      `[INTERNAL] getProvinceAreaRewardDistribution: provinceCode=${provinceCode}, treeCount=${treeCount}`,
    )

    return this.applicationService.getProvinceAreaRewardDistribution(
      provinceCode,
      Number(treeCount),
    )
  }

  /**
   * 获取市团队权益分配方案 (40 USDT)
   */
  @Get('city-team-reward-distribution')
  @ApiOperation({ summary: '获取市团队权益分配方案（内部 API）' })
  @ApiQuery({ name: 'accountSequence', description: '认种用户的 accountSequence' })
  @ApiQuery({ name: 'cityCode', description: '城市代码' })
  @ApiQuery({ name: 'treeCount', description: '认种棵数' })
  async getCityTeamRewardDistribution(
    @Query('accountSequence') accountSequence: string,
    @Query('cityCode') cityCode: string,
    @Query('treeCount') treeCount: string,
  ): Promise<{
    distributions: Array<{
      accountSequence: string
      treeCount: number
      reason: string
    }>
  }> {
    this.logger.debug(
      `[INTERNAL] getCityTeamRewardDistribution: accountSequence=${accountSequence}, cityCode=${cityCode}, treeCount=${treeCount}`,
    )

    return this.applicationService.getCityTeamRewardDistribution(
      accountSequence,
      cityCode,
      Number(treeCount),
    )
  }

  /**
   * 获取市区域权益分配方案 (35 USDT + 2%算力)
   */
  @Get('city-area-reward-distribution')
  @ApiOperation({ summary: '获取市区域权益分配方案（内部 API）' })
  @ApiQuery({ name: 'cityCode', description: '城市代码' })
  @ApiQuery({ name: 'treeCount', description: '认种棵数' })
  async getCityAreaRewardDistribution(
    @Query('cityCode') cityCode: string,
    @Query('treeCount') treeCount: string,
  ): Promise<{
    distributions: Array<{
      accountSequence: string
      treeCount: number
      reason: string
      isSystemAccount: boolean
    }>
  }> {
    this.logger.debug(
      `[INTERNAL] getCityAreaRewardDistribution: cityCode=${cityCode}, treeCount=${treeCount}`,
    )

    return this.applicationService.getCityAreaRewardDistribution(
      cityCode,
      Number(treeCount),
    )
  }

  // =============== 系统账户报表统计 API ===============
  // [2026-01-04] 新增：用于 reporting-service 聚合系统账户报表数据
  // 回滚方式：删除以下 API 方法即可

  /**
   * 获取所有固定系统账户列表
   * 包括：总部社区、成本账户、运营账户、RWAD底池
   */
  @Get('statistics/fixed-accounts')
  @ApiOperation({ summary: '获取固定系统账户列表（内部 API）- 用于系统账户报表' })
  @ApiResponse({ status: 200, description: '固定系统账户列表' })
  async getFixedAccountsList() {
    this.logger.log(`========== statistics/fixed-accounts 请求 ==========`)

    const result = await this.systemAccountService.getAllFixedAccounts()

    this.logger.log(`固定账户查询结果: ${result.length} 个账户`)
    return result
  }

  /**
   * 获取区域系统账户列表
   * 支持按省份或城市类型筛选
   */
  @Get('statistics/region-accounts')
  @ApiOperation({ summary: '获取区域系统账户列表（内部 API）- 用于系统账户报表' })
  @ApiQuery({ name: 'type', description: '账户类型: province 或 city' })
  @ApiResponse({ status: 200, description: '区域系统账户列表' })
  async getRegionAccountsList(
    @Query('type') type: 'province' | 'city',
  ) {
    this.logger.log(`========== statistics/region-accounts 请求 ==========`)
    this.logger.log(`type: ${type}`)

    const result = await this.systemAccountService.getRegionAccountsSummary(type)

    this.logger.log(`区域账户查询结果: ${result.accounts.length} 个账户, 总余额: ${result.summary.totalBalance}`)
    return result
  }

  /**
   * 获取所有系统账户汇总统计
   * 包括固定账户和区域账户的汇总
   */
  @Get('statistics/all-accounts-summary')
  @ApiOperation({ summary: '获取所有系统账户汇总（内部 API）- 用于系统账户报表' })
  @ApiResponse({ status: 200, description: '所有系统账户汇总' })
  async getAllAccountsSummary() {
    this.logger.log(`========== statistics/all-accounts-summary 请求 ==========`)

    const result = await this.systemAccountService.getAllAccountsSummary()

    this.logger.log(`所有账户汇总: 固定${result.fixedAccounts.length}个, 省${result.provinceSummary.count}个, 市${result.citySummary.count}个`)
    return result
  }
}
