require 'uri'
require 'net/http'

class EmailController < ApplicationController
  skip_before_action :verify_authenticity_token
  def index
  end

  def create
    response = requestToNewsLetter(params[:email])
    @email = Email.create(message_params)
    render json: response.body, status: response.code
  end

  def requestToNewsLetter(email)
    $stdout.sync = true
    uri = URI('https://listmonk.bitium.agency/api/subscribers')
    begin
      # Set up the request
      request = Net::HTTP::Post.new(uri)
      request.basic_auth("newsletter", "7c221c667054e442")
      request.set_form_data({
        "email": email,
        "name": "Subscriber",
        "lists": [
            3
        ]
    })
      response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
        http.request(request)
      end
     
    end
    return response
  end
end

  private
  def message_params
    params.permit(:email)
  end