class NotificationsController < ApplicationController
  skip_before_action :require_login
  skip_after_action :verify_authorized, except: :index
  skip_after_action :verify_policy_scoped, only: :index
  skip_before_action :verify_authenticity_token

  def create
    case notification_type

    when "SubscriptionConfirmation"
      Rails.logger.info(subscribe_url)

    when "Notification"
      case job_status
      when "SUCCEEDED" then analysis_notification.success!
      when "FAILED" then analysis_notification.failure!
      else
        Rails.logger.alert "Notification with status #{job_status}\n#{notification}"
      end

    else
      Rails.logger.alert "Notification with type #{notification_type}\n#{notification}"
    end

    head :ok
  end

  private

  # TODO: Verify the message
  def notification
    @notification ||= JSON.parse(request.raw_post)
  end

  def notification_type
    notification.fetch("Type")
  end

  def subscribe_url
    notification.fetch("SubscribeURL")
  end

  def message
    @message ||= JSON.parse(notification.fetch("Message"))
  end

  def job_id
    message.fetch("JobId")
  end

  def job_status
    message.fetch("Status")
  end

  def analysis_type
    message.fetch("AnalysisType")
  end

  def analysis_notification
    @analysis_notification ||= AnalysisNotification.build(analysis_type, job_id)
  end
end
