# frozen_string_literal: true

require 'time'

require 'kisi/mailer'
require 'models/rule'

# The class responsible for the logic behind handling a webhook call.
class Webhook
  attr_accessor :created_at, :action, :object_type, :success, :message, :mailer,
                :actor

  def initialize(json)
    @action = json['action']
    @object_type = json['object_type']
    @created_at = Time.parse(json['created_at'])
    @success = json['success'].eql?('on')
    @message = json.fetch('message', 'carl@kisi.io unlocked lock Entrance Door')
    initialize_actor(json)

    @mailer = KisiMailer.new
  end

  def initialize_actor(json)
    actor_email = json['actor_email']
    actor_id = json['actor_id']

    if actor_email
      @actor = User.where(email: actor_email).first
    elsif actor_id
      @actor = User.where(kisi_id: actor_id).first
    end

    @actor = User.create(email: actor_email, kisi_id: actor_id) if actor.nil?
  end

  def rules
    created_at_time = created_at.hour * 60 + created_at.min

    Rule.matching(created_at_time, action, object_type, success, actor)
  end

  def process
    rules.map do |rule|
      rule.subscribers.each do |subscriber|
        mailer.send_kisi_mail(subscriber, message)
      end

      rule
    end
  end
end
