import axios from 'axios';
import { Injectable } from '@nestjs/common';
import { ConfigurationService } from '../../config/configuration.service';
import { ErrorService } from '../../error/error.service';
import { v4 as uuidv4 } from 'uuid';
import {
  AdvancedDrivingOffenseInquiry,
  BasicDrivingOffenseInquiry,
  FreewayTollInquiry,
} from './ghabzino.interface';

@Injectable()
export class GhabzinoService {
  private axios;

  constructor(
    private config: ConfigurationService,
    private error: ErrorService,
  ) {
    this.axios = axios.create({
      baseURL: 'https://core.inquiry.ayantech.ir/webservices/core.svc',
    });
  }

  /**
   * -------------------------------
   * Freeway Inquiry
   */
  async freewayTollBillInquiry(
    plateNumber: string,
  ): Promise<FreewayTollInquiry> {
    try {
      const [Left, Alphabet, Mid, Iran, Right] = plateNumber.split('***');

      const { data } = await this.axios.post('/FreewayTollBillInquiry', {
        Identity: {
          Token: this.config.thirdParty.ghabzinoToken,
        },
        Parameters: {
          Right,
          Mid,
          Alphabet,
          Left,
        },
      });

      if (data.Status.Code === 'GM4034') {
        return { hasBill: false, bills: [] };
      }

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return { hasBill: true, bills: data.Parameters.Bills };
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Freeway Pay
   */
  async freewayTollBillPay(uniqueIds: string[], mobile: string) {
    try {
      const { data } = await this.axios.post('/ReportNewCarTaxPayment', {
        Identity: {
          Token: this.config.thirdParty.ghabzinoToken,
        },
        Parameters: {
          MobileNumber: mobile,
          Bills: uniqueIds,
          RedirectLinkTitle: 'بازگشت به اتوتیک',
          RedirectLink: 'https://auto-tik.com',
          UniqueKey: '1',
          TerminalID: '3000',
        },
      });

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return {
        bankUrl: data.Parameters.PaymentLink,
        paymentKey: data.Parameters.PaymentKey,
      };
    } catch (e) {
      console.log('Ghabzino catch', e?.response?.data);
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Freeway Pay Result
   */
  async freewayTollBillPayResult(paymentKey: string) {
    try {
      const { data } = await this.axios.post(
        '/CarTaxPaymentInfoCallBackResult',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            PaymentKey: paymentKey,
          },
        },
      );

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return data.Parameters;
    } catch (e) {
      console.log('Ghabzino catch', e?.response?.data);
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Basic Driving Offense Inquiry
   */
  async basicDrivingOffenseInquiry(
    nationalCode: string,
    mobile: string,
    plateNumber: string,
    lastTraceNumber = null,
  ): Promise<BasicDrivingOffenseInquiry> {
    try {
      const [Left, Alphabet, Mid, Iran, Right] = plateNumber.split('***');

      const traceNumber = lastTraceNumber || uuidv4();

      const { data } = await this.axios.post(
        '/TrafficFinesInquiryByPlateNumberNoDetail',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
            Right,
            Mid,
            Alphabet,
            Left,
          },
        },
      );
      if (data.Status.Code !== 'G00000' && data.Status.Code !== 'GM5031') {
        throw data.Status.Description;
      }

      return {
        TraceNumber: traceNumber,
        PlateNumber: data.Parameters.PlateNumber,
        TotalAmount: data.Parameters.Amount,
        TotalBillId: data.Parameters.BillID,
        TotalPayId: data.Parameters.PaymentID,
        ComplaintCode: data.Parameters.ComplaintCode,
        ComplaintStatus: data.Parameters.ComplaintStatus,
      };
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      // this.error.internalServerError([
      //   typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      // ]);
      return null;
    }
  }

  /**
   * -------------------------------
   * Advanced Driving Offense Inquiry
   */
  async advancedDrivingOffenseInquiry(
    nationalCode: string,
    mobile: string,
    plateNumber: string,
  ): Promise<AdvancedDrivingOffenseInquiry> {
    try {
      const [Left, Alphabet, Mid, Iran, Right] = plateNumber.split('***');

      const traceNumber = uuidv4();

      const { data } = await this.axios.post(
        '/TrafficFinesInquiryByPlateNumber',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
            Right,
            Mid,
            Alphabet,
            Left,
          },
        },
      );

      if (data.Status.Code !== 'G00000' && data.Status.Code !== 'GM5031') {
        throw data.Status.Description;
      }

      return {
        TraceNumber: traceNumber,
        PlateNumber: data.Parameters.PlateNumber,
        TotalAmount: data.Parameters.TotalAmount,
        TotalBillId: data.Parameters.BillID,
        TotalPayId: data.Parameters.PaymentID,
        Bills: data.Parameters.Details.map((detail) => ({
          Amount: detail.Amount,
          BillId: detail.BillID,
          PayId: detail.PaymentID,
          City: detail.City,
          Location: detail.Location,
          Type: detail.Type,
          TypeId: detail.TypeCode,
          Date: detail.DateTime,
          DeliveryType: detail.Delivery,
          SerialNumber: detail.SerialNumber,
          OfficerIdentificationCode: detail.OfficerIdentificationCode,
          ImageId: detail?.HasImage ? detail?.UniqueID || null : null,
        })),
      };
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      // this.error.internalServerError([
      //   typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      // ]);
      return null;
    }
  }

  /**
   * -------------------------------
   * get Driving Offense Image
   */
  async getDrivingOffenseImage(mobile: string, uniqueID: string) {
    try {
      const traceNumber = uuidv4();

      const { data } = await this.axios.post('/TrafficFinesInquiryGetImage', {
        Identity: {
          Token: this.config.thirdParty.ghabzinoToken,
        },
        Parameters: {
          TraceNumber: traceNumber,
          UniqueID: uniqueID,
          MobileNumber: mobile,
          WalletIdentifier: mobile,
        },
      });

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return {
        traceNumber: traceNumber,
        PlateImageUrl: data.Parameters.PlateImageUrl,
        VehicleImageUrl: data.Parameters.VehicleImageUrl,
      };
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Negative Score Inquiry (Naji Service)
   */
  async negativeScoreInquiry(
    nationalCode: string,
    mobile: string,
    licenseNumber: string,
  ) {
    try {
      const traceNumber = uuidv4();

      const { data } = await this.axios.post(
        '/NajiServiceDrivingLicenseNegativePointInquiry',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            LicenseNumber: licenseNumber,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
          },
        },
      );

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return {
        traceNumber: traceNumber,
        AllowedToDrive: data.Parameters.AllowedToDrive,
        NegativeScore: data.Parameters.Point,
        Rule: data.Parameters.Rule,
      };
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Driving License Status Inquiry  (Naji Service)
   */
  async drivingLicensestatusInquiry(nationalCode: string, mobile: string) {
    try {
      const traceNumber = uuidv4();

      // console.log({
      //   TraceNumber: traceNumber,
      //   NationalID: nationalCode,
      //   MobileNumber: mobile,
      //   WalletIdentifier: mobile,
      // });

      const { data } = await this.axios.post(
        '/NajiServiceDrivingLicenseStatusInquiry',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
          },
        },
      );

      console.log('data', data.Parameters);

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      // [
      // "Barcode": "21692008717048354340",
      // "DateTime": "03/17/2018 00:00:00",
      // "FirstName": "محمد جواد",
      // "LastName": "مسعوديان",
      // "NationalID": "1870245008",
      // "Number": "9607777573",
      // "Status": "اسکن شده ناجي پاس",
      // "Type": "پايه سوم",
      // "ValidityPeriodInYears": "10"
      // ]

      return data.Parameters?.Licenses || [];
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * pay driving offense bill
   */
  async payDrivingOffenseBill(bills, mobile: string) {
    try {
      const { data } = await this.axios.post('/ReportNewBillPayment', {
        Identity: {
          Token: this.config.thirdParty.ghabzinoToken,
        },
        Parameters: {
          MobileNumber: mobile,
          Bills: bills,
          RedirectLinkTitle: 'بازگشت به اتوتیک',
          RedirectLink: 'https://auto-tik.com',
          UniqueKey: '1',
          TerminalID: '11',
        },
      });

      console.log({
        MobileNumber: mobile,
        Bills: bills,
        RedirectLinkTitle: 'بازگشت به اتوتیک',
        RedirectLink: 'https://auto-tik.com',
        UniqueKey: '1',
        TerminalID: '11',
      });

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return {
        bankUrl: data.Parameters.PaymentLink,
        paymentKey: data.Parameters.PaymentKey,
        bills: data.Parameters.Bills,
      };
    } catch (e) {
      console.log('Ghabzino catch', e === 'string' ? e : e?.response?.data);
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------------------------------
   * POST /driving-offenses/1/pay-result-bills/me
   */
  async resultDrivingOffenseBill(paymentKey: string, lastTraceNumber = null) {
    try {
      const traceNumber = lastTraceNumber || uuidv4();

      const { data } = await this.axios.post('/BillPaymentInfoCallBackResult', {
        Identity: {
          Token: this.config.thirdParty.ghabzinoToken,
        },
        Parameters: {
          TraceNumber: traceNumber,
          PaymentKey: paymentKey,
        },
      });

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      return data.Parameters;
    } catch (e) {
      console.log('Ghabzino catch', e?.response?.data);
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Car Identification Documents Status Inquiry (Naji Service)
   */
  async carIdentificationDocumentsStatusInquiry(
    nationalCode: string,
    mobile: string,
    plateNumber: string,
    lastTraceNumber = null,
  ) {
    try {
      const [Left, Alphabet, Mid, Iran, Right] = plateNumber.split('***');

      const traceNumber = lastTraceNumber || uuidv4();

      const { data } = await this.axios.post(
        '/NajiServiceCarIdentificationDocumentsStatusInquiry',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
            Right,
            Mid,
            Alphabet,
            Left,
          },
        },
      );

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      // "CardDateTime": "12/11/2014 00:00:00",
      // "CardPostalBarcode": "18539000617001882310",
      // "CardTitle": "چاپ شده",
      // "DocumentDateTime": "12/11/2014 00:00:00",
      // "DocumentTitle": "صدور",
      // "PlateNumber": "ایران ۱۴ - ۳۵۱ ل  ۹۳"

      return data.Parameters;
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }

  /**
   * -------------------------------
   * Plate Numbers Inquiry (Naji Service)
   */
  async plateNumbersInquiry(
    nationalCode: string,
    mobile: string,
    lastTraceNumber = null,
  ) {
    try {
      const traceNumber = lastTraceNumber || uuidv4();

      const { data } = await this.axios.post(
        '/NajiServicePlateNumbersInquiry',
        {
          Identity: {
            Token: this.config.thirdParty.ghabzinoToken,
          },
          Parameters: {
            TraceNumber: traceNumber,
            NationalID: nationalCode,
            MobileNumber: mobile,
            WalletIdentifier: mobile,
          },
        },
      );

      if (data.Status.Code !== 'G00000') {
        throw data.Status.Description;
      }

      // "data": {
      //   "PlateNumbers": [
      //     {
      //       "NationalID": "1870245008",
      //       "PlateNumber": "ایران ۱۴ - ۳۵۱ ل  ۹۳",
      //       "Revoked": false,
      //       "RevokedDateTime": null,
      //       "RevokedDescription": null,
      //       "SerialNumber": "10100427081343"
      //     },
      //     {
      //       "NationalID": "1870245008",
      //       "PlateNumber": "ایران ۲۰ - ۱۱۴ ی  ۹۹",
      //       "Revoked": true,
      //       "RevokedDateTime": "08/02/2022 13:59:56",
      //       "RevokedDescription": "شماره گذاري کاشان",
      //       "SerialNumber": "10100237007451"
      //     }
      //   ]
      // }

      return data.Parameters;
    } catch (e) {
      console.log(
        'Ghabzino catch',
        typeof e === 'string' ? e : e?.response?.data,
      );
      this.error.internalServerError([
        typeof e === 'string' ? e : 'خطایی در اتصال به سرور رخ داده است',
      ]);
    }
  }
}
