import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { GetInfoByIdsDto } from './dto/get-info-by-ids.dto';
import { GetPriceDto } from './dto/get-price.dto';

const testJson = {
  Products: [
    {
      ProductID: '1064',
      Variables: [
        {
          VariableName: 'Tiefe',
          VariableValue: 250,
        },
        {
          VariableName: 'Breite',
          VariableValue: 300,
        },
        {
          VariableName: 'HoeheOKT',
          VariableValue: 250,
        },
      ],
    },
    {
      ProductID: '1072',
      Variables: [
        {
          VariableName: 'Tiefe',
          VariableValue: 250,
        },
        {
          VariableName: 'Breite',
          VariableValue: 300,
        },
      ],
    },
    {
      ProductID: '1165',
    },
    {
      ProductID: '1240',
    },
    {
      ProductID: '1178',
    },
    {
      ProductID: '1043',
    },
    {
      ProductID: '1059',
      Variables: [
        {
          VariableName: 'Breite',
          VariableValue: 276,
        },
        {
          VariableName: 'Hoehe',
          VariableValue: 230,
        },
      ],
    },
    {
      ProductID: '1059',
      Variables: [
        {
          VariableName: 'Breite',
          VariableValue: 226,
        },
        {
          VariableName: 'Hoehe',
          VariableValue: 230,
        },
      ],
    },
    {
      ProductID: '1059',
      Variables: [
        {
          VariableName: 'Breite',
          VariableValue: 276,
        },
        {
          VariableName: 'Hoehe',
          VariableValue: 230,
        },
      ],
    },
    {
      ProductID: '1059',
      Variables: [
        {
          VariableName: 'Breite',
          VariableValue: 226,
        },
        {
          VariableName: 'Hoehe',
          VariableValue: 230,
        },
      ],
    },
    {
      ProductID: '1005',
    },
    {
      ProductID: '1008',
    },
    {
      ProductID: '1090',
    },
    {
      ProductID: '1094',
    },
    {
      ProductID: '1097',
    },
  ],
};

@Injectable()
export class CrmService {
  private readonly logger = new Logger(this.constructor.name);
  private readonly crmApiUrl =
    'https://cloud.thermogreen.ch/rest/prsproductservice/v1';
  private readonly APIKey = '?APIKey=';

  constructor(
    private readonly configService: ConfigService,
    private readonly httpService: HttpService,
  ) {
    this.APIKey += this.configService.get('CRM_KEY');
  }

  async getPrice(body: GetPriceDto) {
    try {
      const Products = await this._transformOrderToBody(body.products);

      const response = await this.httpService.axiosRef.post(
        `${this.crmApiUrl}/GetProducts${this.APIKey}`,
        {
          Products,
        },
      );
      return {
        prices: response.data.WS_Products?.map((item, index) => ({
          ...item,
          side: body.products[index]?.side,
          section: body.products[index]?.section,
          sectionLenght: body.products[index]?.sectionLenght,
          squar: body.products[index]?.squar,
        })),
      };
    } catch (e) {
      this.logger.error(e.message);
      return {
        error: true,
        message: e.message,
      };
    }
  }

  async getInfoByIds(body: GetInfoByIdsDto) {
    try {
      const products = await Promise.all(
        body.products.map(async (id) => {
          const response = await this.httpService.axiosRef.get(
            `${this.crmApiUrl}/GetProductInfo/${id}${this.APIKey}`,
          );

          return response.data;
        }),
      );

      return {
        products,
      };
    } catch (e) {
      this.logger.error(e.message);
      return {
        error: true,
        message: e.message,
      };
    }
  }

  private async _transformOrderToBody(order: any[]) {
    const { products } = await this.getInfoByIds({
      products: order.map((el) => el.id),
    });

    return order.map((el) => {
      const product = {
        ProductID: String(el.id),
        Variables: undefined,
      };

      const info = products.find((product) => product.ProductNo === el.id);

      if (info?.WS_ProductVariables) {
        product.Variables = info?.WS_ProductVariables.map((v) => {
          const isHave = el?.Variables
            ? el.Variables.find((vChild) => vChild.VariableName === v.Name)
            : false;

          if (isHave) {
            return isHave;
          }

          return {
            VariableName: v.Name,
            VariableValue: v.Value,
          };
        });
      }

      return product;
    });
  }
}
