import { Controller, Post, Body, Get, Param, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiProperty } from '@nestjs/swagger';
import { IsArray, IsString } from 'class-validator';
import { Public } from '@/shared/guards/jwt-auth.guard';
import { UserAccountRepositoryImpl } from '@/infrastructure/persistence/repositories/user-account.repository.impl';
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service';
import { AccountSequence } from '@/domain/value-objects';

/**
 * 批量获取用户信息请求 DTO (按 accountSequence)
 */
class BatchGetUsersBySequenceDto {
  @ApiProperty({ description: '账户序列号列表', example: ['2412230001', '2412230002'] })
  @IsArray()
  @IsString({ each: true })
  accountSequences: string[];
}

/**
 * 用户基本信息响应
 */
interface UserBasicInfo {
  userId: string;
  accountSequence: string;
  nickname: string;
  avatarUrl?: string;
}

/**
 * 用户详情信息响应（包含敏感信息，仅内部调用）
 */
interface UserDetailInfo {
  userId: string;
  accountSequence: string;
  nickname: string;
  avatarUrl?: string;
  phoneNumber?: string;  // 敏感信息
  email?: string;        // 敏感信息
  registeredAt: string;
  inviterSequence?: string;  // 推荐人序列号
  kycStatus: string;
  realName?: string;     // 敏感信息
  idCardNumber?: string; // 敏感信息 - 用于合同签署
}

/**
 * 内部服务调用控制器
 * 用于微服务间的内部通信，不需要JWT认证
 */
@ApiTags('Internal')
@Controller('internal')
export class InternalController {
  private readonly logger = new Logger(InternalController.name);

  constructor(
    private readonly userRepository: UserAccountRepositoryImpl,
    private readonly prisma: PrismaService,
  ) {}

  @Public()
  @Post('users/batch')
  @ApiOperation({ summary: '批量获取用户信息（内部调用，按 accountSequence）' })
  @ApiResponse({ status: 200, description: '返回用户信息列表' })
  async batchGetUsers(@Body() dto: BatchGetUsersBySequenceDto): Promise<UserBasicInfo[]> {
    this.logger.debug(`[batchGetUsers] 请求用户数量: ${dto.accountSequences?.length || 0}`);

    if (!dto.accountSequences || dto.accountSequences.length === 0) {
      return [];
    }

    try {
      const sequences = dto.accountSequences.map((seq) => AccountSequence.create(seq));
      const users = await this.userRepository.findByAccountSequences(sequences);

      const result = users.map((user) => ({
        userId: user.userId.value.toString(),
        accountSequence: user.accountSequence.value,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl || undefined,
      }));

      this.logger.debug(`[batchGetUsers] 返回用户数量: ${result.length}`);
      return result;
    } catch (error) {
      this.logger.error(`[batchGetUsers] 查询失败:`, error);
      return [];
    }
  }

  @Public()
  @Get('users/:accountSequence/detail')
  @ApiOperation({ summary: '获取用户详情（内部调用，包含敏感信息）' })
  @ApiResponse({ status: 200, description: '返回用户详情信息' })
  async getUserDetailBySequence(@Param('accountSequence') accountSequence: string): Promise<UserDetailInfo | null> {
    this.logger.debug(`[getUserDetailBySequence] 查询用户详情: ${accountSequence}`);

    try {
      // 直接使用 Prisma 查询以获取所有字段（包括 email、realName 等领域模型中未暴露的字段）
      const user = await this.prisma.userAccount.findUnique({
        where: { accountSequence },
      });

      if (!user) {
        return null;
      }

      return {
        userId: user.userId.toString(),
        accountSequence: user.accountSequence,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl || undefined,
        phoneNumber: user.phoneNumber || undefined,
        email: user.email || undefined,
        registeredAt: user.registeredAt.toISOString(),
        inviterSequence: user.inviterSequence || undefined,
        kycStatus: user.kycStatus,
        realName: user.realName || undefined,
        idCardNumber: user.idCardNumber || undefined,
      };
    } catch (error) {
      this.logger.error(`[getUserDetailBySequence] 查询失败:`, error);
      return null;
    }
  }

  @Public()
  @Get('users/:accountSequence')
  @ApiOperation({ summary: '获取单个用户信息（内部调用，按 accountSequence）' })
  @ApiResponse({ status: 200, description: '返回用户信息' })
  async getUserBySequence(@Param('accountSequence') accountSequence: string): Promise<UserBasicInfo | null> {
    this.logger.debug(`[getUserBySequence] 查询用户: ${accountSequence}`);

    try {
      const sequence = AccountSequence.create(accountSequence);
      const user = await this.userRepository.findByAccountSequence(sequence);

      if (!user) {
        return null;
      }

      return {
        userId: user.userId.value.toString(),
        accountSequence: user.accountSequence.value,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl || undefined,
      };
    } catch (error) {
      this.logger.error(`[getUserBySequence] 查询失败:`, error);
      return null;
    }
  }
}
