import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DefaultCreditLimit } from './defaultcreaditlimit.entity';
import { Repository } from 'typeorm';
import { RpcException } from '@nestjs/microservices';

@Injectable()
export class DefaultcreaditlimitService {
  constructor(
    @InjectRepository(DefaultCreditLimit)
    private repo: Repository<DefaultCreditLimit>,
  ) {}

  async getAll(): Promise<DefaultCreditLimit[]> {
    return this.repo.find();
  }

  async getById(id: number): Promise<DefaultCreditLimit> {
    const item = await this.repo.findOneBy({ idDefault_Credit_Limit: id });
    if (!item) {
      throw new RpcException({
        message: 'Credit limit entry not found',
        statusCode: 404,
      });
    }
    return item;
  }

  async add(body: any): Promise<any> {
    const created = this.repo.create(body);
    const data = await this.repo.save(created);
    return {
      message: 'Default credit limit entry added!',
      data,
    };
  }

  async update(id: number, body: any): Promise<any> {
    const item = await this.repo.findOneBy({ idDefault_Credit_Limit: id });
    if (!item) {
      throw new RpcException({
        message: 'Credit limit entry not found',
        statusCode: 404,
      });
    }
    const updated = Object.assign(item, body);
    await this.repo.save(updated);
    return {
      message: 'updating completed!',
      data: updated,
    };
  }
}
