import { Injectable } from '@nestjs/common';
import { TypeOrmCrudService } from '@dataui/crud-typeorm';
import { Category } from './entities/category.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class CategoryService extends TypeOrmCrudService<Category> {
  constructor(@InjectRepository(Category) repo) {
    super(repo);
  }

  async getNestedCategories() {
    const categories = await this.repo.find({ relations: { parentCategory: true, icon: true } });

    //nest the multilevel categories by parent
    const nestedCategories: Partial<Category>[] = [];
    categories.forEach((category) => {
      if (!category.parentCategory) {
        nestedCategories.push(category);
      } else {
        const parent = categories.find((el) => el.id == category.parentCategory?.id);
        if (parent) {
          if (!parent.subCategories) {
            parent.subCategories = [];
          }
          delete category.parentCategory;// for a cleaner data in frontend
          parent.subCategories.push(category);
        }
      }
    });

    //add level to each category
    nestedCategories.forEach((category: Partial<Category> & { level: number }) => {
      return this.appendNestedLevel(category);
    });

    return nestedCategories;
  }

  appendNestedLevel(category: Partial<Category> & { level: number }, level = 0) {
    category.level = level;
    if (category.subCategories) {
      category.subCategories.forEach((subCategory: Partial<Category> & { level: number }) => {
        this.appendNestedLevel(subCategory, level + 1);
      });
    }
    return category;
  }



}
