import axios from 'axios';
import { Injectable } from '@nestjs/common';
import { ConfigurationService } from '../../config/configuration.service';
import * as moment from 'jalali-moment';

@Injectable()
export class SshafService {
  private axios;

  constructor(private config: ConfigurationService) {
    const token = this.config.thirdParty.sshafToken;
    const gregorianDate = moment().format('YYYYMMDD'); // Get current Gregorian date
    const persianDate = moment().locale('fa').format('YYYYMMDD'); // Get current Persian date

    const authorization = Buffer.from(
      token + +gregorianDate * +persianDate,
    ).toString('base64');

    this.axios = axios.create({
      baseURL: 'https://apisshaf.727433.ir/rest',
      headers: { authorization },
    });
  }

  // -------------------------------------
  async setOil(
    roleCode: string,
    postalCode: string,
    sellerPhone: string,
    sellerNationalCode: string,
    list: SetOil[],
  ) {
    try {
      const { data } = await this.axios.post(
        '/setoil',
        list.map((item) => ({
          ...item,
          RoleCode: roleCode,
          PostalCode: postalCode,
          SellerPhone: sellerPhone,
          SellerNationalCode: sellerNationalCode,
          SellDate: moment(item.sellDate).locale('fa').format('YYYY/MM/DD'),
          BuyerNationalCode: item.buyerNationalCode,
          BuyerFullName: item.buyerFullName,
          BuyerMobile: item.buyerMobile,
          CodeKala: item.productCode,
          Count: item.count,
          PerPrice: item.perPrice,
          TotalPrice: item.totalPrice,
          ProductInfo: item.productInfo,
          BuyerAddress: item.buyerAddress,
          CarPlateNumber: item.carPlateNumber,
        })),
      );

      if (+data.success === 1) {
        return (
          data?.message || 'درخواست شما با موفقیت به سامانه شفافیت ارسال شد'
        );
      }

      throw new Error();
    } catch (e) {
      console.log('Sshaf catch', e);
      throw {
        data: e?.response?.data?.errors || null,
        message:
          typeof e === 'string'
            ? e
            : e?.response?.data?.message || 'خطایی رخ داده است',
      };
    }
  }
}

// -------------------------------------------------
export interface SetOil {
  sellDate: string;
  buyerNationalCode: string;
  buyerFullName: string;
  buyerMobile: string;
  count: number;
  perPrice: number;
  totalPrice: number;
  productCode: string;
  productInfo: string;
  buyerAddress: string;
  carPlateNumber: string;
}
