import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { ReferralStat } from '../../domain/entities/referral-stat.entity';

@Injectable()
export class ReferralStatRepository {
  private readonly repo: Repository<ReferralStat>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = this.dataSource.getRepository(ReferralStat);
  }

  async findByTenantId(tenantId: string): Promise<ReferralStat | null> {
    return this.repo.findOne({ where: { tenantId } });
  }

  async upsert(tenantId: string): Promise<ReferralStat> {
    let stat = await this.repo.findOne({ where: { tenantId } });
    if (!stat) {
      stat = this.repo.create({ tenantId });
      await this.repo.save(stat);
    }
    return stat;
  }

  async incrementDirectCount(tenantId: string): Promise<void> {
    await this.repo.upsert(
      { tenantId, directCount: 1 },
      { conflictPaths: ['tenantId'], skipUpdateIfNoValuesChanged: false },
    );
    await this.repo.increment({ tenantId }, 'directCount', 1);
  }

  async incrementActiveCount(tenantId: string): Promise<void> {
    await this.repo.increment({ tenantId }, 'activeCount', 1);
  }

  async addCreditEarned(tenantId: string, cents: number): Promise<void> {
    await this.repo.increment({ tenantId }, 'totalCreditEarned', cents);
    await this.repo.increment({ tenantId }, 'pendingCredit', cents);
  }

  async markCreditApplied(tenantId: string, cents: number): Promise<void> {
    await this.repo.increment({ tenantId }, 'totalCreditApplied', cents);
    await this.repo.decrement({ tenantId }, 'pendingCredit', cents);
  }

  /** Recalculate pendingCredit from actual reward rows (for consistency repair) */
  async recalculatePending(tenantId: string, pendingCents: number): Promise<void> {
    await this.repo.update({ tenantId }, { pendingCredit: pendingCents });
  }
}
