import { Injectable } from '@nestjs/common';
import { ReferralCodeRepository } from '../../infrastructure/repositories/referral-code.repository';

export interface ValidateReferralCodeResult {
  valid: boolean;
  referrerTenantId?: string;
}

@Injectable()
export class ValidateReferralCodeUseCase {
  constructor(private readonly codeRepo: ReferralCodeRepository) {}

  async execute(code: string): Promise<ValidateReferralCodeResult> {
    if (!code || !/^IT0-[A-Z0-9]{3}-[A-Z0-9]{4}$/.test(code)) {
      return { valid: false };
    }

    const entity = await this.codeRepo.findByCode(code);
    if (!entity) {
      return { valid: false };
    }

    // Increment click count asynchronously (don't block response)
    this.codeRepo.incrementClickCount(entity.id).catch(() => {});

    return {
      valid: true,
      referrerTenantId: entity.tenantId,
    };
  }
}
