import { Controller, Get, Put, Param, Body, Query, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service';
import { CapabilityService } from '@/application/services/capability.service';
import { Capability, ALL_CAPABILITIES } from '@/domain/value-objects/capability.vo';

/**
 * 内部 API - 供 2.0 服务间调用，不需要 JWT 认证
 */
@Controller('internal')
export class InternalController {
  private readonly logger = new Logger(InternalController.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly capabilityService: CapabilityService,
  ) {}

  /**
   * 根据 accountSequence 获取用户的 Kava 地址
   * trading-service 创建卖单时调用
   */
  @Get('users/:accountSequence/kava-address')
  async getUserKavaAddress(
    @Param('accountSequence') accountSequence: string,
  ): Promise<{ kavaAddress: string }> {
    // 1. 通过 SyncedLegacyUser 查找 legacyId
    const legacyUser = await this.prisma.syncedLegacyUser.findUnique({
      where: { accountSequence },
      select: { legacyId: true },
    });

    if (!legacyUser) {
      this.logger.warn(`[Internal] Legacy user not found: ${accountSequence}`);
      throw new NotFoundException(`用户未找到: ${accountSequence}`);
    }

    // 2. 通过 legacyUserId + chainType 查找 KAVA 钱包地址
    const walletAddress = await this.prisma.syncedWalletAddress.findUnique({
      where: {
        legacyUserId_chainType: {
          legacyUserId: legacyUser.legacyId,
          chainType: 'KAVA',
        },
      },
      select: { address: true, status: true },
    });

    if (!walletAddress || walletAddress.status !== 'ACTIVE') {
      this.logger.warn(`[Internal] Kava address not found for: ${accountSequence}`);
      throw new NotFoundException(`未找到 Kava 钱包地址: ${accountSequence}`);
    }

    return { kavaAddress: walletAddress.address };
  }

  // =========================================================================
  // 能力权限管理 (供 mining-admin-service 调用)
  // =========================================================================

  /**
   * 获取用户能力权限列表
   */
  @Get('capabilities/:accountSequence')
  async getUserCapabilities(
    @Param('accountSequence') accountSequence: string,
  ) {
    return this.capabilityService.getCapabilities(accountSequence);
  }

  /**
   * 设置用户单个能力
   */
  @Put('capabilities/:accountSequence')
  async setCapability(
    @Param('accountSequence') accountSequence: string,
    @Body() body: {
      capability: string;
      enabled: boolean;
      reason?: string;
      operatorId?: string;
      expiresAt?: string;
    },
  ) {
    this.validateCapability(body.capability);
    return this.capabilityService.setCapability({
      accountSequence,
      capability: body.capability as Capability,
      enabled: body.enabled,
      reason: body.reason,
      operatorId: body.operatorId,
      expiresAt: body.expiresAt ? new Date(body.expiresAt) : undefined,
    });
  }

  /**
   * 批量设置用户能力
   */
  @Put('capabilities/:accountSequence/bulk')
  async bulkSetCapabilities(
    @Param('accountSequence') accountSequence: string,
    @Body() body: {
      capabilities: Array<{
        capability: string;
        enabled: boolean;
        reason?: string;
        expiresAt?: string;
      }>;
      operatorId?: string;
    },
  ) {
    for (const c of body.capabilities) {
      this.validateCapability(c.capability);
    }
    return this.capabilityService.setCapabilities({
      accountSequence,
      capabilities: body.capabilities.map((c) => ({
        capability: c.capability as Capability,
        enabled: c.enabled,
        reason: c.reason,
        expiresAt: c.expiresAt ? new Date(c.expiresAt) : undefined,
      })),
      operatorId: body.operatorId,
    });
  }

  /**
   * 查询用户能力变更日志
   */
  @Get('capabilities/:accountSequence/logs')
  async getCapabilityLogs(
    @Param('accountSequence') accountSequence: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.capabilityService.getCapabilityLogs(
      accountSequence,
      parseInt(page || '1', 10),
      parseInt(pageSize || '20', 10),
    );
  }

  private validateCapability(capability: string): void {
    if (!ALL_CAPABILITIES.includes(capability as Capability)) {
      throw new BadRequestException(
        `无效的能力类型: ${capability}，有效值: ${ALL_CAPABILITIES.join(', ')}`,
      );
    }
  }
}
