import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { Payment, PaymentStatus } from '../../domain/entities/payment.entity';
import { PaymentMethod } from '../../domain/entities/payment-method.entity';

@Injectable()
export class PaymentRepository {
  private readonly paymentRepo: Repository<Payment>;
  private readonly methodRepo: Repository<PaymentMethod>;

  constructor(private readonly dataSource: DataSource) {
    this.paymentRepo = this.dataSource.getRepository(Payment);
    this.methodRepo = this.dataSource.getRepository(PaymentMethod);
  }

  async findPaymentById(id: string): Promise<Payment | null> {
    return this.paymentRepo.findOne({ where: { id } });
  }

  async findByProviderPaymentId(providerPaymentId: string): Promise<Payment | null> {
    return this.paymentRepo.findOne({ where: { providerPaymentId } });
  }

  async findPaymentsByTenantId(tenantId: string, limit = 20): Promise<Payment[]> {
    return this.paymentRepo.find({
      where: { tenantId },
      order: { createdAt: 'DESC' },
      take: limit,
    });
  }

  async savePayment(payment: Payment): Promise<Payment> {
    return this.paymentRepo.save(payment);
  }

  // Payment Methods
  async findMethodsByTenantId(tenantId: string): Promise<PaymentMethod[]> {
    return this.methodRepo.find({
      where: { tenantId },
      order: { isDefault: 'DESC', createdAt: 'ASC' },
    });
  }

  async findMethodById(id: string): Promise<PaymentMethod | null> {
    return this.methodRepo.findOne({ where: { id } });
  }

  async saveMethod(method: PaymentMethod): Promise<PaymentMethod> {
    return this.methodRepo.save(method);
  }

  async deleteMethod(id: string): Promise<void> {
    await this.methodRepo.delete(id);
  }

  async clearDefaultMethods(tenantId: string): Promise<void> {
    await this.methodRepo.update({ tenantId, isDefault: true }, { isDefault: false });
  }
}
