import { Injectable } from '@nestjs/common';
import { ConfigService as CSL } from '@nestjs/config';
import axios from 'axios';
import { ConfigService } from '../config/config.service';
import { mapToProduct } from 'src/features/product';
import { ProductsService } from '../products/products.service';
import { EConfig } from 'src/system/enum/config-enum';
import AppResponse from 'src/system/response/app-response';
import { SystemLang } from 'src/system/lang/system.lang';
import { Product } from 'src/entities/product.entity';
import * as _ from 'lodash';
@Injectable()
export class SyncService {
  constructor(
    private readonly csl: CSL,
    private readonly configAppService: ConfigService,
    private readonly productService: ProductsService,
  ) {}

  async sync() {
    const limit = await this.configAppService.repo.findOne({
      where: { key_name: EConfig.LIMIT },
    });

    const { data } = await axios({
      headers: { Authorization: `Bearer ${this.csl.get('VITE_API_TOKEN')}` },
      url: 'transferGetData',
      baseURL: this.csl.get('BASE_URL'),
      method: 'POST',
      data: {
        urlAPI: '/api/ebay-listing/listing-get-list',
        filter: {
          skip: 0,
          limit: limit?.value || 4180,
          order: 'updatedAt desc',
          where: {
            account: 'prology_net',
            status: 'Updated',
            productModelCode: '',
          },
        },
      },
    });

    const rawProducts = data?.data || [];

    const productsToSave = rawProducts.map((item: any) => {
      return this.productService.repo.create(mapToProduct(item) as any);
    });

    const result = await this.productService.repo.upsert(productsToSave, [
      'ebayListingId',
    ]);

    if (data?.total && data?.total != limit?.value) {
      if (!limit) {
        await this.configAppService.repo.save({
          key_name: EConfig.LIMIT,
          value: data?.total,
        });
      } else {
        await this.configAppService.repo.update(
          { key_name: EConfig.LIMIT },
          {
            key_name: EConfig.LIMIT,
            value: data?.total,
          },
        );
      }
    }

    return AppResponse.toResponse(true, {
      message: SystemLang.getText('messages', 'success'),
    });
  }
}
