import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MerchantCategory } from './merchantcategory.entity';
import { Repository } from 'typeorm';

@Injectable()
export class MerchantcategoryService {
  constructor(
    @InjectRepository(MerchantCategory)
    private MerchantCategoryRepo: Repository<MerchantCategory>,
  ) {}

  async getAll(): Promise<MerchantCategory[]> {
    const data = await this.MerchantCategoryRepo.find();
    return data;
  }

  async getById(id: number): Promise<MerchantCategory> {
    const data = this.MerchantCategoryRepo.findOneBy({
      idMerchantCategory: id,
    });
    return data;
  }

  async createMerchantCategory(body: any): Promise<any> {
    const merchantCategory = this.MerchantCategoryRepo.create(body);
    const data = await this.MerchantCategoryRepo.save(merchantCategory);
    return {
      data: data,
      message: 'Merchant Category Adding Completed!',
    };
  }

  async updateMerchantCategory(id: number, body: any): Promise<any> {
    const existing = await this.MerchantCategoryRepo.findOneBy({
      idMerchantCategory: id,
    });
    if (!existing) {
      throw new Error('Merchant category Not Found!');
    }

    const updated = Object.assign(existing, body);
    const saved = await this.MerchantCategoryRepo.save(updated);
    return {
      data: saved,
      message: 'Merchant Category Updating Completed!',
    };
  }
}
