import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { UserReferralCodeRepository } from '../../infrastructure/repositories/user-referral-code.repository';
import { UserReferralRelationshipRepository } from '../../infrastructure/repositories/user-referral-relationship.repository';
import { UserPointRepository } from '../../infrastructure/repositories/user-point.repository';

export interface UserReferralInfo {
  code: string;
  shareUrl: string;
  circleSize: number;        // total direct invitees (level-1)
  activeCount: number;       // those who have paid
  pointsBalance: number;
  totalEarned: number;
  totalSpent: number;
}

@Injectable()
export class GetMyUserReferralInfoUseCase {
  constructor(
    private readonly codeRepo: UserReferralCodeRepository,
    private readonly relRepo: UserReferralRelationshipRepository,
    private readonly pointRepo: UserPointRepository,
    private readonly config: ConfigService,
  ) {}

  async execute(userId: string): Promise<UserReferralInfo> {
    // Ensure code exists (create if first visit)
    const codeEntity = await this.codeRepo.findByUserId(userId)
      ?? await this.codeRepo.createForUser(userId);

    const appUrl = this.config.get<string>('APP_URL', 'https://it0.szaiai.com');
    const shareUrl = `${appUrl}/join?ref=${codeEntity.code}`;

    const { items, total } = await this.relRepo.findByReferrerUserId(userId, 1000, 0);
    const activeCount = items.filter((r) => r.status !== 'PENDING' && r.status !== 'EXPIRED').length;

    const balance = await this.pointRepo.getBalance(userId);

    return {
      code: codeEntity.code,
      shareUrl,
      circleSize: total,
      activeCount,
      pointsBalance: balance.balance,
      totalEarned: balance.totalEarned,
      totalSpent: Math.abs(balance.totalSpent),
    };
  }
}
