import axios from 'axios';
import { Injectable } from '@nestjs/common';
import { ConfigurationService } from '../../config/configuration.service';
import { ErrorService } from '../../error/error.service';
import { v4 as uuid } from 'uuid';

@Injectable()
export class MahexService {
  private axios;
  private isSandbox = false;

  constructor(
    private config: ConfigurationService,
    private error: ErrorService,
  ) {
    this.isSandbox = config.thirdParty.mahexMode === 'sandbox';

    this.axios = axios.create({
      baseURL:
        config.thirdParty.mahexMode === 'sandbox'
          ? 'http://api.mahex.com'
          : 'http://api.mahex.com',
      headers: {
        Authorization: `Basic ${this.config.thirdParty.mahexToken}`,
      },
      proxy: false,
    });
  }

  /////////////////////////////////////////////////////////////////
  async getPrice(street: string, cityCode: string, weights: number[]) {
    try {
      const payload = {
        to_address: {
          street,
          city_code: cityCode,
        },
        parcels: weights.map((w) => ({
          weight: this.isSandbox ? 1 : w,
        })),
      };
      console.log('payload', payload);

      const { data } = await this.axios.post('/v2/rates', payload);

      return data;
    } catch (e) {
      console.log('Mahex catch', e?.response?.data);
      this.error.internalServerError([
        'خطایی در محاسبه هزینه پستی رخ داده است',
      ]);
    }
  }

  /////////////////////////////////////////////////////////////////
  async createOrder(
    street: string,
    cityCode: string,
    parcels: any,
    fistName: string,
    lastName: string,
    mobile: string,
  ) {
    try {
      const { data } = await this.axios.post('/v2/shipments', {
        to_address: {
          street,
          city_code: cityCode,
          first_name: fistName,
          last_name: lastName,
          phone: mobile,
          type: 'LEGAL',
        },
        parcels: parcels.map((parcel) => ({
          id: parcel.id,
          weight: this.isSandbox ? 1 : parcel.weight,
          content: parcel.category,
        })),
        reference: uuid(),
      });

      return data;
    } catch (e) {
      console.log('Mahex catch', e?.response?.data);
      this.error.internalServerError(['خطایی در سمت ماهکس رخ داده است']);
    }
  }

  /////////////////////////////////////////////////////////////////
  async getDetail(shipmentUuid) {
    try {
      const { data } = await this.axios.get(`/v2/shipments/${shipmentUuid}`);
      return data;
    } catch (e) {
      console.log('Mahex catch', e?.response?.data);
      this.error.internalServerError(['خطایی در سمت ماهکس رخ داده است']);
    }
  }

  /////////////////////////////////////////////////////////////////
  async getTrack(waybillNumber) {
    try {
      const { data } = await this.axios.get(`/v2/track/${waybillNumber}`);
      return data;
    } catch (e) {
      console.log('Mahex catch', e?.response?.data);
      this.error.internalServerError(['خطایی در سمت ماهکس رخ داده است']);
    }
  }

  // /////////////////////////////////////////////////////////////////
  // async getAll(page = 1, perpage = 15) {
  //   try {
  //     const { data } = await this.axios.get(`/orders`, {
  //       params: { page, perpage },
  //     });
  //     return data;
  //   } catch (e) {
  //     console.log('Mahex catch', e?.response?.data);
  //     this.error.internalServerError(['خطایی در سمت ماهکس رخ داده است']);
  //   }
  // }

  // ////////////////////////////////////////////////////////////////
  // async cancelOrder(orderId) {
  //   try {
  //     const { data } = await this.axios.get(`/orders/${orderId}/cancel`);
  //     return data;
  //   } catch (e) {
  //     console.log('Mahex catch', e?.response?.data);
  //     this.error.internalServerError(['خطایی در سمت ماهکس رخ داده است']);
  //   }
  // }
}
