class ZoomMeeting < ApplicationRecord
  belongs_to :project, optional: true
  belongs_to :zoom_user

  has_one_attached :recording
  validates :recording, content_type: ['video/mp4']

  enum status: [:created, :started, :ended]

  after_create :create_api_meeting, if: -> { api_meeting_id.nil? }

  scope :active, -> { where(status: %i[created started]).order(status: :desc) }

  def meeting
    @meeting ||= get_api_meeting
  end

  def start_url
    meeting['start_url']
  end

  def join_url
    meeting['join_url']
  end

  def meeting_url
    if started?
      join_url
    elsif created? || ended?
      start_url
    end
  end

private

  def get_api_meeting
    create_api_meeting unless self.api_meeting_id.present?
    gateway.find_meeting(self.api_meeting_id)
  rescue ZoomGateway::MeetingExpired => e
    # The meeting has expired but it is attempted to be accessed.
    # New meeting is needed, the old one needs to be kept track of.
    # Creating new meeting and saving it as a new record.
    duplicate = self.dup
    duplicate.api_meeting_id = nil
    duplicate.save
    self.id = duplicate.id
    reload
    retry
  end

  def create_api_meeting
    self.api_meeting_id = gateway.create_meeting(zoom_user.api_id, topic: meeting_topic)
    self.status = :created
    save
  rescue ZoomGateway::UserNotFound => e
    zoom_user.create_api_user
    retry
  end

  def gateway
    @gateway ||= ZoomGateway.new
  end

  def meeting_topic
    if project.present?
      "Conference for DirectME project: #{project.name}"
    else
      "Conference for DirectME project"
    end
  end
end
