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

@Injectable()
export class MerchanttypeService {
  constructor(
    @InjectRepository(MerchantType)
    private merchantTypeRepo: Repository<MerchantType>,
  ) {}

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

  async getById(id: number): Promise<MerchantType> {
    const data = this.merchantTypeRepo.findOneBy({
      idMerchantType: id,
    });
    return data;
  }

  async createMerchantType(body: any): Promise<any> {
    const merchantType = this.merchantTypeRepo.create(body); //this will create object  comment by isuru
    const data = await this.merchantTypeRepo.save(merchantType);
    return {
      data: data,
      message: 'Merchant Type Adding completed!',
    };
  }

  async updateMerchantType(id: number, body: any): Promise<any> {
    const existing = await this.merchantTypeRepo.findOneBy({
      idMerchantType: id,
    });

    if (!existing) {
      throw new Error('Merchant Type Not Found!');
    }
    const updated = Object.assign(existing, body);
    const saved = await this.merchantTypeRepo.save(updated);
    return {
      data: saved,
      message: 'Merchant Type Updating Completed!',
    };
  }
}
