/**
 * Account information PNZ-API-CentreLib
 *
 * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ).
 */

import { ApiResponse, RequestOptions } from '../core';
import {
  HFAC8Exchangeauthorizationcodeforaccesstoken,
  hFAC8ExchangeauthorizationcodeforaccesstokenSchema,
} from '../models/hFAC8Exchangeauthorizationcodeforaccesstoken';
import { string } from '../schema';
import { BaseController } from './baseController';
import {v4 as uuidv4} from 'uuid';
import { ClientAssertionJWT } from '../utils';

export class RefreshTokenController extends BaseController {
  /**
   * @param clientID
   * @param privateKey
   * @param KID
   * @param refreshToken
   * @return Response from the API call
   */
  async refreshAccessToken(
    clientID: string,
    privateKey: string,
    KID: string,
    refreshToken: string,
    requestOptions?: RequestOptions
  ): Promise<ApiResponse<HFAC8Exchangeauthorizationcodeforaccesstoken>> {
    const req = this.createRequest('POST', '/oauth/v2.0/token');
    const grantType = 'refresh_token';
    const scope = 'openid accounts';
    const clientAssertionType = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
    const payload: {
      sub: string;
      aud: string;
      iss: string;
      exp: number;
      iat: number;
      jti: string;
      } = {
      sub: clientID,
      aud: "https://api-nomatls.apicentre.middleware.co.nz/oauth/v2.0/token",
      iss: clientID,
      exp: Math.floor(Date.now() / 1000) + 2000,
      iat: Math.floor(Date.now() / 1000) - 120,
      jti: uuidv4()
      };
    const clientAssertion = ClientAssertionJWT(privateKey,KID,payload);
    const mapped = req.prepareArgs({
      grantType: [grantType, string()],
      refreshToken: [refreshToken, string()],
      scope: [scope, string()],
      clientAssertionType: [clientAssertionType, string()],
      clientAssertion: [clientAssertion, string()],
    });
    req.header('content-type', 'application/x-www-form-urlencoded');
    req.form({
      grant_type: mapped.grantType,
      refresh_token: mapped.refreshToken,
      scope: mapped.scope,
      client_assertion_type: mapped.clientAssertionType,
      client_assertion: mapped.clientAssertion,
    });
    return req.callAsJson(
      hFAC8ExchangeauthorizationcodeforaccesstokenSchema,
      requestOptions
    );
  }
}
