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

@Injectable()
export class InitializationService {
  private readonly logger = new Logger(InitializationService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly configService: ConfigService,
  ) {}

  async initializeMiningConfig(
    adminId: string,
    config: {
      totalShares: string;
      distributionPool: string;
      halvingPeriodYears: number;
      burnTarget: string;
    },
  ): Promise<{ success: boolean; message: string }> {
    const record = await this.prisma.initializationRecord.create({
      data: { type: 'MINING_CONFIG', status: 'PENDING', config, executedBy: adminId },
    });

    try {
      // 调用 mining-service API 初始化配置
      const miningServiceUrl = this.configService.get<string>('MINING_SERVICE_URL', 'http://localhost:3021');
      const response = await fetch(`${miningServiceUrl}/api/v1/admin/initialize`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      });

      if (!response.ok) {
        throw new Error('Failed to initialize mining config');
      }

      await this.prisma.initializationRecord.update({
        where: { id: record.id },
        data: { status: 'COMPLETED', executedAt: new Date() },
      });

      await this.prisma.auditLog.create({
        data: { adminId, action: 'INIT', resource: 'MINING', resourceId: record.id, newValue: config },
      });

      return { success: true, message: 'Mining config initialized successfully' };
    } catch (error: any) {
      await this.prisma.initializationRecord.update({
        where: { id: record.id },
        data: { status: 'FAILED', errorMessage: error.message },
      });

      return { success: false, message: error.message };
    }
  }

  async initializeSystemAccounts(adminId: string): Promise<{ success: boolean; message: string }> {
    const accounts = [
      { accountType: 'OPERATION', name: '运营账户', description: '12% 运营收入' },
      { accountType: 'PROVINCE', name: '省公司账户', description: '1% 省公司收入' },
      { accountType: 'CITY', name: '市公司账户', description: '2% 市公司收入' },
    ];

    for (const account of accounts) {
      await this.prisma.systemAccount.upsert({
        where: { accountType: account.accountType },
        create: account,
        update: { name: account.name, description: account.description },
      });
    }

    await this.prisma.auditLog.create({
      data: { adminId, action: 'INIT', resource: 'SYSTEM_ACCOUNT', newValue: accounts },
    });

    return { success: true, message: 'System accounts initialized successfully' };
  }

  async activateMining(adminId: string): Promise<{ success: boolean; message: string }> {
    try {
      const miningServiceUrl = this.configService.get<string>('MINING_SERVICE_URL', 'http://localhost:3021');
      const response = await fetch(`${miningServiceUrl}/api/v1/admin/activate`, { method: 'POST' });

      if (!response.ok) {
        throw new Error('Failed to activate mining');
      }

      await this.prisma.auditLog.create({
        data: { adminId, action: 'INIT', resource: 'MINING', newValue: { action: 'ACTIVATE' } },
      });

      return { success: true, message: 'Mining activated successfully' };
    } catch (error: any) {
      return { success: false, message: error.message };
    }
  }
}
