import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ShopItemCategory } from './shopitemcategory.entity';

@Injectable()
export class ShopItemCategoryService {
  constructor(
    @InjectRepository(ShopItemCategory)
    private categoryRepo: Repository<ShopItemCategory>,
  ) {}

  async add(data: any): Promise<any> {
    const newCategory = this.categoryRepo.create(data);
    await this.categoryRepo.save(newCategory);
    return { success: true, message: 'Category created successfully' };
  }

  async getAll(): Promise<ShopItemCategory[]> {
    return await this.categoryRepo.find();
  }

  async getById(id: number): Promise<ShopItemCategory> {
    const category = await this.categoryRepo.findOneBy({ idShop_Item_Category: id });
    if (!category) {
      throw new NotFoundException('Category not found');
    }
    return category;
  }

  async update(id: number, data: any): Promise<any> {
    const existing = await this.categoryRepo.findOneBy({ idShop_Item_Category: id });
    if (!existing) {
      throw new NotFoundException('Category not found');
    }

    const updated = this.categoryRepo.merge(existing, data);
    await this.categoryRepo.save(updated);

    return { success: true, message: 'Category updated successfully' };
  }

  async getByMerchantId(merchantId: number): Promise<ShopItemCategory[]> {
    return await this.categoryRepo.findBy({ Merchant_idMerchant: merchantId });
  }
}
