import { Injectable } from '@nestjs/common';
import { ReferralCodeRepository } from '../../infrastructure/repositories/referral-code.repository';
import { ReferralStatRepository } from '../../infrastructure/repositories/referral-stat.repository';
import { ReferralRewardRepository } from '../../infrastructure/repositories/referral-reward.repository';
import { ReferralRelationshipRepository } from '../../infrastructure/repositories/referral-relationship.repository';

export interface MyReferralInfoDto {
  referralCode: string;
  shareUrl: string;
  directCount: number;
  activeCount: number;
  pendingCreditCents: number;
  totalEarnedCents: number;
  totalAppliedCents: number;
}

@Injectable()
export class GetMyReferralInfoUseCase {
  constructor(
    private readonly codeRepo: ReferralCodeRepository,
    private readonly statRepo: ReferralStatRepository,
  ) {}

  async execute(tenantId: string, userId: string): Promise<MyReferralInfoDto> {
    // Ensure the tenant has a referral code; auto-create if not
    let codeEntity = await this.codeRepo.findByTenantId(tenantId);
    if (!codeEntity) {
      codeEntity = await this.codeRepo.create(tenantId, userId);
    }

    // Ensure stats row exists
    const stat = await this.statRepo.upsert(tenantId);

    const appUrl = process.env.APP_REFERRAL_BASE_URL || 'https://it0api.szaiai.com';

    return {
      referralCode: codeEntity.code,
      shareUrl: `${appUrl}/register?ref=${codeEntity.code}`,
      directCount: stat.directCount,
      activeCount: stat.activeCount,
      pendingCreditCents: stat.pendingCredit,
      totalEarnedCents: stat.totalCreditEarned,
      totalAppliedCents: stat.totalCreditApplied,
    };
  }
}
