import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ShopItem } from './shopitem.entity';

@Injectable()
export class ShopService {
  constructor(
    @InjectRepository(ShopItem)
    private shopItemRepo: Repository<ShopItem>,
  ) {}

  async getAll(): Promise<ShopItem[]> {
    return await this.shopItemRepo.find();
  }

  async add(data: any): Promise<any> {
    const shopItem = this.shopItemRepo.create(data);
    await this.shopItemRepo.save(shopItem);
    return { success: true, message: 'Shop item created successfully' };
  }

  async getById(id: number): Promise<ShopItem> {
    const item = await this.shopItemRepo.findOneBy({ idShop_Item: id });
    if (!item) {
      throw new NotFoundException('Shop item not found');
    }
    return item;
  }

  async update(id: number, data: any): Promise<any> {
    const existingItem = await this.shopItemRepo.findOneBy({ idShop_Item: id });
    if (!existingItem) {
      throw new NotFoundException('Shop item not found');
    }

    const updatedItem = this.shopItemRepo.merge(existingItem, data);
    await this.shopItemRepo.save(updatedItem);

    return { success: true, message: 'Shop item updated successfully' };
  }

  async getShopItemByMerchantId(merchantId: number): Promise<ShopItem[]> {
    return await this.shopItemRepo.findBy({
      Merchant_idMerchant: merchantId,
    });
  }
}
