const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

class Client {
  constructor() {
    this.BASE_URL = 'https://api-sandbox.yousign.app/v3';
    this.API_KEY = 'REPLACE_WITH_YOUR_API_KEY';
  }

  request = async(
    endpoint = '',
    options = {},
    headers = {}
  ) => {
    const url = `${this.BASE_URL}/${endpoint}`;
    const config = {
      url,
      headers: {
        Authorization: `Bearer ${this.API_KEY}`,
        ...headers
      },
      ...options
    }

    try {
      const res = await axios(config);
      return res.data;
    } catch (e) {
      throw new Error(`Error on API call`);
    }
  }

  // Initiate Signature Request
  initiateSignatureRequest = () => {
    const body = {
      name: "Signature request example",
      delivery_mode: 'email',
      timezone: 'Europe/Paris',
    };
    const options = {
      method: 'POST',
      data: JSON.stringify(body),
    };
    const headers = {
      'Content-type': 'application/json',
    };
    return this.request('signature_requests', options, headers);
  }

  // Upload Document
  uploadDocument = (signatureRequestId) => {
    const form = new FormData();
    form.append('file', fs.createReadStream('test.pdf'), {
      filename: 'test.pdf',
    });
    form.append('nature', 'signable_document');
    form.append('parse_anchors', 'true');

    const options = {
      method: 'POST',
      data: form,
    };
    const headers = form.getHeaders();
    return this.request(`signature_requests/${signatureRequestId}/documents`, options, headers);
  }

  // Add Signer
  addSigner = (signatureRequestId, documentId) => {
    const body = {
      info: {
        first_name: 'John',
        last_name: 'Doe',
        email: '[email protected]',
        phone_number: '+33601234567',
        locale: 'fr',
      },
      signature_level: 'electronic_signature',
      signature_authentication_mode: 'no_otp',
      fields: [
        {
          document_id: documentId,
          type: 'signature',
          page: 1,
          x: 77,
          y: 581,
        }
      ]
    };
    const options = {
      method: 'POST',
      data: JSON.stringify(body),
    };
    const headers = {
      'Content-type': 'application/json',
    };
    return this.request(`signature_requests/${signatureRequestId}/signers`, options, headers);
  }

  // Activate Signature Request
  activateSignatureRequest = (signatureRequestId) => {
    const options = {
      method: 'POST',
    }
    return this.request(`signature_requests/${signatureRequestId}/activate`, options);
  }
}

module.exports = {
  Client,
}