import { Controller } from '@nestjs/common';
import { MessagePattern, RpcException } from '@nestjs/microservices';
import { ShopitemsubcategoryService } from './shopitemsubcategory.service';

@Controller()
export class ShopItemSubCategoryController {
  constructor(private readonly service: ShopitemsubcategoryService) {}

  @MessagePattern({ cmd: 'shop_item_sub_category_add' })
  async add(data: { body: any }) {
    try {
      return await this.service.add(data.body);
    } catch (err) {
      throw new RpcException('Failed to add sub-category');
    }
  }

  @MessagePattern({ cmd: 'shop_item_sub_category_get_all' })
  async getAll(data: { protocol: string; host: string }) {
    try {
      const { protocol, host } = data;
      const result = await this.service.getAll();
      const baseurl = `${protocol}://${host}/uploads/shop/sub-category-icons/`;

      const data2 = await Promise.all(
        result.map(async (item) => {
          const Icon_Url = item.Icon_Path ? baseurl + item.Icon_Path : null;
          return {
            ...item,
            Icon_Url,
          };
        }),
      );
      return data2;
    } catch (err) {
      throw new RpcException('Failed to get sub-categories');
    }
  }

  @MessagePattern({ cmd: 'shop_item_sub_category_get_by_id' })
  async getById(data: { id: number; protocol: string; host: string }) {
    try {
      const { id, protocol, host } = data;
      const baseurl = `${protocol}://${host}/uploads/shop/sub-category-icons/`;
      const result = await this.service.getById(id);
      const data2 = await Promise.all(
        result.map(async (item) => {
          const Icon_Url = item.Icon_Path ? baseurl + item.Icon_Path : null;
          return {
            ...item,
            Icon_Url,
          };
        }),
      );

      return data2;
    } catch (err) {
      throw new RpcException('Failed to get sub-category by ID');
    }
  }

  @MessagePattern({ cmd: 'shop_item_sub_category_update' })
  async update(data: { id: number; body: any }) {
    try {
      return await this.service.update(data.id, data.body);
    } catch (err) {
      throw new RpcException('Failed to update sub-category');
    }
  }
}
