import { Injectable, NotFoundException } from '@nestjs/common';
import { ShopItemSubCategory } from './shopitemsubcategory.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class ShopitemsubcategoryService {
  constructor(
    @InjectRepository(ShopItemSubCategory)
    private readonly repo: Repository<ShopItemSubCategory>,
  ) {}

  async add(data: any): Promise<any> {
    const subCat = this.repo.create(data);
    await this.repo.save(subCat);
    return { success: true, message: 'Sub-category added successfully' };
  }
  async getAll(): Promise<ShopItemSubCategory[]> {
    return await this.repo.find();
  }

  async getById(id: number): Promise<any> {
    const item = await this.repo.findOneBy({ idShopItemSubCategory: id });

    return item ? [item] : [];
  }

  async update(id: number, data: any): Promise<any> {
    const existing = await this.repo.findOneBy({ idShopItemSubCategory: id });
    if (!existing) {
      throw new NotFoundException('Sub-category not found');
    }

    // Only update Icon_Path if it's included in the data
    if (!data.Icon_Path) {
      delete data.Icon_Path;
    }

    const updated = this.repo.merge(existing, data);
    await this.repo.save(updated);
    return { success: true, message: 'Sub-category updated successfully' };
  }
}
