import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service';
import { OutboxService } from './outbox.service';
import { LegacyUserMigratedEvent } from '@/domain';

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

  constructor(
    private readonly prisma: PrismaService,
    private readonly outboxService: OutboxService,
  ) {}

  /**
   * 获取所有用户数据供 mining-admin-service 同步
   */
  async getAllUsersForSync(): Promise<{
    users: Array<{
      id: string;
      accountSequence: string;
      phone: string;
      status: string;
      kycStatus: string;
      realName: string | null;
      isLegacyUser: boolean;
      createdAt: string;
    }>;
  }> {
    // 获取已注册到 2.0 的用户
    const users = await this.prisma.user.findMany({
      select: {
        id: true,
        accountSequence: true,
        phone: true,
        status: true,
        kycStatus: true,
        realName: true,
        createdAt: true,
      },
    });

    // 获取从 1.0 同步的但尚未迁移的用户
    const legacyUsers = await this.prisma.syncedLegacyUser.findMany({
      where: {
        accountSequence: {
          notIn: users.map((u) => u.accountSequence),
        },
      },
      select: {
        legacyId: true,
        accountSequence: true,
        phone: true,
        status: true,
        legacyCreatedAt: true,
      },
    });

    const allUsers = [
      ...users.map((u) => ({
        id: String(u.id),
        accountSequence: u.accountSequence,
        phone: u.phone,
        status: u.status,
        kycStatus: u.kycStatus,
        realName: u.realName,
        isLegacyUser: false,
        createdAt: u.createdAt.toISOString(),
      })),
      ...legacyUsers.map((u) => ({
        id: String(u.legacyId),
        accountSequence: u.accountSequence,
        phone: u.phone || '',
        status: u.status,
        kycStatus: 'PENDING',
        realName: null,
        isLegacyUser: true,
        createdAt: u.legacyCreatedAt?.toISOString() || new Date().toISOString(),
      })),
    ];

    return { users: allUsers };
  }

  /**
   * 为所有 synced_legacy_users 发布 user.legacy.migrated 事件
   * 用于初始同步到 mining-admin-service
   */
  async publishAllLegacyUsers(): Promise<{
    success: boolean;
    publishedCount: number;
    failedCount: number;
    message: string;
  }> {
    const legacyUsers = await this.prisma.syncedLegacyUser.findMany({
      select: {
        accountSequence: true,
        phone: true,
        nickname: true,
        legacyCreatedAt: true,
      },
    });

    let publishedCount = 0;
    let failedCount = 0;

    for (const user of legacyUsers) {
      try {
        const event = new LegacyUserMigratedEvent(
          user.accountSequence,
          user.phone || '',
          user.nickname || '',
          user.legacyCreatedAt || new Date(),
        );
        await this.outboxService.publish(event);
        publishedCount++;
        this.logger.debug(`Published event for legacy user: ${user.accountSequence}`);
      } catch (error) {
        failedCount++;
        this.logger.error(`Failed to publish event for legacy user: ${user.accountSequence}`, error);
      }
    }

    this.logger.log(`Published ${publishedCount} legacy user events, ${failedCount} failed`);

    return {
      success: failedCount === 0,
      publishedCount,
      failedCount,
      message: `Published ${publishedCount} events, ${failedCount} failed out of ${legacyUsers.length} total`,
    };
  }
}
