import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Wallet } from '../../domain/entities/wallet.entity';
import { IWalletRepository } from '../../domain/repositories/wallet.repository.interface';

@Injectable()
export class WalletRepository implements IWalletRepository {
  constructor(@InjectRepository(Wallet) private readonly repo: Repository<Wallet>) {}

  async findByUserId(userId: string): Promise<Wallet | null> {
    return this.repo.findOne({ where: { userId } });
  }

  async create(userId: string, currency: string = 'USD'): Promise<Wallet> {
    const wallet = this.repo.create({ userId, currency, balance: '0', frozenBalance: '0', status: 'active' });
    return this.repo.save(wallet);
  }

  async save(wallet: Wallet): Promise<Wallet> {
    return this.repo.save(wallet);
  }

  async findByUserIdWithLock(userId: string): Promise<Wallet | null> {
    return this.repo
      .createQueryBuilder('wallet')
      .setLock('pessimistic_write')
      .where('wallet.userId = :userId', { userId })
      .getOne();
  }
}
