import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';

/**
 * 预种卖出限制管理服务（mining-admin-service 侧）
 *
 * [2026-03-04] 新增：管理员手动解除用户的预种卖出限制，并记录审计日志。
 *
 * === 调用链 ===
 * mining-admin-web → mining-admin-service (本服务) → contribution-service
 *
 * === 审计记录 ===
 * 每次解除操作均写入 AuditLog，保证可追溯性。
 */
@Injectable()
export class PrePlantingRestrictionService {
  private readonly logger = new Logger(PrePlantingRestrictionService.name);
  private readonly contributionServiceUrl: string;

  constructor(
    private readonly prisma: PrismaService,
    private readonly configService: ConfigService,
  ) {
    this.contributionServiceUrl = this.configService.get<string>(
      'CONTRIBUTION_SERVICE_URL',
      'http://localhost:3020',
    );
  }

  /**
   * 查询账户的预种卖出限制状态
   */
  async getRestrictionStatus(accountSequence: string): Promise<{ isRestricted: boolean }> {
    const url = `${this.contributionServiceUrl}/api/v2/pre-planting/sell-restriction/${accountSequence}`;
    const response = await fetch(url, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
      signal: AbortSignal.timeout(5000),
    });

    if (!response.ok) {
      throw new Error(`contribution-service returned ${response.status}`);
    }

    const data = (await response.json()) as { data?: { isRestricted: boolean }; isRestricted?: boolean };
    const isRestricted = data?.data?.isRestricted ?? data?.isRestricted ?? false;
    return { isRestricted };
  }

  /**
   * 管理员手动解除预种卖出限制
   *
   * 调用 contribution-service 写入 override 记录，并在本地写入审计日志。
   *
   * @param adminId 执行操作的管理员 ID（来自 JWT）
   * @param accountSequence 被解除限制的用户账户序列
   * @param reason 解除原因（可选）
   */
  async unlockRestriction(adminId: string, accountSequence: string, reason?: string, ipAddress?: string, userAgent?: string): Promise<void> {
    // 1. 调用 contribution-service 写入 override
    const url = `${this.contributionServiceUrl}/api/v2/pre-planting/sell-restriction/${accountSequence}/unlock`;
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ unlockedBy: adminId, reason }),
      signal: AbortSignal.timeout(5000),
    });

    if (!response.ok) {
      const text = await response.text().catch(() => '');
      throw new Error(`contribution-service unlock failed (${response.status}): ${text}`);
    }

    this.logger.log(`Admin ${adminId} unlocked pre-planting sell restriction for ${accountSequence}`);

    // 2. 写入审计日志（严格审计：每次操作必须记录）
    await this.prisma.auditLog.create({
      data: {
        adminId,
        action: 'UNLOCK',
        resource: 'PRE_PLANTING_SELL_RESTRICTION',
        resourceId: accountSequence,
        newValue: { reason: reason ?? null, unlockedBy: adminId },
        ipAddress,
        userAgent,
      },
    });
  }
}
