import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TetardCoin } from './entities/tetard-coin.entity';
import { Transaction } from './entities/transaction.entity';

@Injectable()
export class TetardCoinService {
  constructor(
    @InjectRepository(TetardCoin)
    private readonly tcRepo: Repository<TetardCoin>,
    @InjectRepository(Transaction)
    private readonly txRepo: Repository<Transaction>,
  ) {}

  async getBalance(userId: string): Promise<number> {
    const record = await this.tcRepo.findOne({ where: { userId } });
    return record?.balance ?? 0;
  }

  async earn(userId: string, amount: number, reason = 'earn'): Promise<number> {
    if (amount <= 0) throw new BadRequestException('earn amount must be > 0');

    let record = await this.tcRepo.findOne({ where: { userId } });
    if (!record) {
      record = this.tcRepo.create({ userId, balance: 0 });
    }
    record.balance += amount;
    await this.tcRepo.save(record);
    await this.txRepo.save(this.txRepo.create({ userId, amount, reason }));
    return record.balance;
  }

  async spend(userId: string, amount: number, reason: string): Promise<number> {
    if (amount <= 0) throw new BadRequestException('spend amount must be > 0');

    const record = await this.tcRepo.findOne({ where: { userId } });
    const current = record?.balance ?? 0;

    // Invariant absolu : balance ne peut jamais être négative
    if (current < amount) {
      throw new BadRequestException(
        `Insufficient balance: has ${current} TC, needs ${amount} TC`,
      );
    }

    record!.balance -= amount;
    await this.tcRepo.save(record!);
    await this.txRepo.save(this.txRepo.create({ userId, amount: -amount, reason }));
    return record!.balance;
  }
}
