import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PaymentMethods } from './paymentmethods.entity';
import { Repository } from 'typeorm';

@Injectable()
export class PaymentmethodsService {
  constructor(
    @InjectRepository(PaymentMethods)
    private readonly paymentRepo: Repository<PaymentMethods>,
  ) {}

  async getAll(): Promise<PaymentMethods[]> {
    return await this.paymentRepo.find({
      order: { idPayment_Methods: 'DESC' },
    });
  }

  async getByCustomerId(customerId: number): Promise<PaymentMethods[]> {
    return await this.paymentRepo.find({
      where: { Customer_idCustomer: customerId },
      order: { idPayment_Methods: 'DESC' },
    });
  }

  async add(data: any): Promise<any> {
    const method = this.paymentRepo.create(data);
    await this.paymentRepo.save(method);
    return { success: true, message: 'Payment method added' };
  }

  async getById(id: number): Promise<PaymentMethods | null> {
    return await this.paymentRepo.findOneBy({ idPayment_Methods: id });
  }

  async update(id: number, data: any): Promise<any> {
    console.log(id);
    console.log(data);

    const existing = await this.paymentRepo.findOneBy({
      idPayment_Methods: id,
    });

    if (!existing) {
      return { success: false, message: 'Payment method not found' };
    }

    const { idPayment_Methods, id: _, ...safeData } = data;

    await this.paymentRepo.update({ idPayment_Methods: id }, safeData);

    return { success: true, message: 'Payment method updated' };
  }
}
