class User < ApplicationRecord
  has_many :assistant_threads
  has_many :assistant_conversations
  has_many :transcript_highlights, dependent: :destroy
  has_attached_file :photo, default_url: "/default_avatar.png"
  validates_attachment_content_type :photo, content_type: %r{\Aimage/.*\z}

  scope :active, -> { where(active: true) }
  scope :inactive, -> { where(active: false) }

  belongs_to :organization
  has_many :projects, through: :organization
  devise :database_authenticatable,
         :rememberable, :validatable, :trackable

  delegate :feature_enabled?, to: :organization

  # overridden devise method
  def active_for_authentication?
    super && active?
  end

  # overridden devise method
  def inactive_message
    active? ? super : :account_deactivated
  end

  def self.user_from_encrypted_link(encrypted_link)
    data = JSON.parse(SymmetricEncryptorService.decrypt(encrypted_link))
    user_id = data["studio_user_id"]
    User.find(user_id)
  rescue StandardError => e
    Rails.logger.fatal("Error in decryption: #{e.message}")
    nil
  end

  def name
    "#{first_name} #{last_name}"
  end

  def remember_me
    super.nil? ? true : super
  end

  def developer?
    ["fareesh@intemlabs.com", "bhavin@intemlabs.com"].include? email
  end

  def fareesh?
    first_name == "Fareesh"
  end

  def sprint_user?
    organization_id == 1 || developer?
  end

  def admin?
    role == "admin"
  end
end
