class CreditReport::ApplicationService < ApplicationService
  def initialize(school, model, options={})
    @school = school
    @model = model
    @options = options
  end

  private
    def payload
      {
        username: Rails.application.secrets.credit_report[:username],
        password: Rails.application.secrets.credit_report[:password]
      }
    end

    def base_url
      Rails.application.secrets.credit_report[:base_url]
    end

    def url
      "#{base_url}/#{endpoint}"
    end

    def headers
      {
        'Authorization' => "Bearer #{token}",
        'Content-Type' => 'application/json'
      }
    end

    def token
      resp = RestClient.post("#{base_url}/users/login", payload.to_json, {'Content-Type' => 'application/json' })
      JSON.parse(resp.body)['token']
    end

    def rest_client_request(method, path, model, area, body: {})
      response = RestClient::Request.execute(
        method: method,
        url: path,
        headers: headers,
        payload: body.to_json
      )
      status_code = response.code
      response_body = JSON.parse(response.body)
      response
    rescue RestClient::Exception => e
      status_code = e.http_code
      response_body = e.response&.body
      nil
    ensure
      model.connection_logs.create!(
        school: @school,
        service: :credit_report,
        area: area,
        http_method: method,
        status_code: status_code,
        endpoint: endpoint.slice(0, 100),
        response: response_body&.slice(0, 1000),
        payload: body
      )
    end
end
