class Tep::ApplicationService < ApplicationService
  def initialize(school, id=nil, options={})
    @school = school
    @id = id
    @options = options
  end

  private
    def id_token
      JWT.encode(payload, hmac_key, 'HS256', alg: 'HS256', typ: 'JWT')
    end

    def payload
      {
        school_id: @school.id,
        time: Time.zone.now.to_i
      }
    end

    def hmac_key
      Rails.application.secrets.tep[:key]
    end

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

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

    def headers
      {
        Authorization: "Bearer #{id_token}",
        'Content-Type' => 'application/json'
      }
    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: :tep,
        area: area,
        http_method: method,
        status_code: status_code,
        endpoint: path,
        response: response_body.slice(0, 1000),
        payload: body
      )
    end
end
