import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CustomerSavings } from './customersavings.entity';
import { Repository } from 'typeorm';

@Injectable()
export class CustomersavingsService {
  constructor(
    @InjectRepository(CustomerSavings)
    private readonly savingsRepo: Repository<CustomerSavings>,
  ) {}

  async getAll(): Promise<CustomerSavings[]> {
    return await this.savingsRepo.find();
  }

  async getById(id: number): Promise<CustomerSavings | null> {
    return await this.savingsRepo.findOneBy({ idCustomer_Savings: id });
  }

  async add(data: any): Promise<any> {
    const savings = this.savingsRepo.create(data);
    await this.savingsRepo.save(savings);
    return { success: true, message: 'Customer savings added successfully' };
  }

  async update(id: number, data: any): Promise<any> {
    const existing = await this.savingsRepo.findOneBy({
      idCustomer_Savings: id,
    });
    if (!existing) {
      return { success: false, message: 'Savings record not found' };
    }

    const { idCustomer_Savings, id: _, ...safeData } = data;
    await this.savingsRepo.update({ idCustomer_Savings: id }, safeData);

    return { success: true, message: 'Customer savings updated successfully' };
  }

  async getByCustomerId(customerId: number): Promise<CustomerSavings[]> {
    return await this.savingsRepo.find({
      where: { Customer_idCustomer: customerId },
      order: { idCustomer_Savings: 'DESC' },
    });
  }
}
