import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MerchantHasCategories } from './merchant-has-category.entity';
import { Repository } from 'typeorm';

@Injectable()
export class MerchantHasCategoryService {
  constructor(
    @InjectRepository(MerchantHasCategories)
    private merchantHasCategoryRepo: Repository<MerchantHasCategories>,
  ) {}

  async addMerchantHasCategories(
    Merchant_idMerchant: number,
    MerchantCategory_idMerchantCategory: number,
  ): Promise<any> {
    const merchantHasCategory = this.merchantHasCategoryRepo.create({
      Merchant_idMerchant,
      MerchantCategory_idMerchantCategory,
    });

    const data = await this.merchantHasCategoryRepo.save(merchantHasCategory);
    return data;
  }

  async deleteExistingCategoriesById(id: number): Promise<any> {
    const deleteit = await this.merchantHasCategoryRepo.delete({
      Merchant_idMerchant: id,
    });

    return {
      message: 'Merchant has categories deleted successfully!',
      affected: deleteit,
    };
  }

  async getMerchantHasCategoriesByMerchantId(
    Merchant_idMerchant: number,
  ): Promise<any> {
    console.log('The merchgant id in srvice : ', Merchant_idMerchant);
    const fetchedData = await this.merchantHasCategoryRepo.query(
      `SELECT mhc.*,mc.Description FROM merchant_has_categories mhc INNER JOIN merchant_category mc ON mhc.MerchantCategory_idMerchantCategory = mc.idMerchantCategory WHERE mhc.Merchant_idMerchant = ?`,
      [Merchant_idMerchant],
    );
    console.log(fetchedData);

    return fetchedData;
  }
}
