module Subscriptions
  class BadgeTimeoutStatus < Subscriptions::Base
    attributes :channel_id, :expires_on, :timed_out

    def self.find_by(channel_id:)
      response = get "/internal/channels/#{channel_id}/badge_timeout/status"

      return self.new unless response.success? && response.body.is_a?(Hash)

      timeout_status = response.body
      timeout_status[:channel_id] = channel_id

      from_attributes(timeout_status)
    end

    def update(params)
      params[:expires_on] = normalize_date_string(params[:expires_on])
      params[:timed_out] = params[:timed_out].present?

      response = put "/internal/channels/#{channel_id}/badge_timeout/status", body: params.to_json

      unless response.success? && response.body.is_a?(Hash)
        errors.add(:base, response.body["error"])
      end

      response.success?
    end

    private

    def normalize_date_string(string)
      Time.parse(string).utc.to_datetime.rfc3339 rescue nil
    end
  end
end
