module Brandable
  extend ActiveSupport::Concern

  HEX_COLOR = /\A#[0-9A-Fa-f]{6}\z/

  included do
    has_one_attached :logo_file
    validates :primary_color, format: { with: HEX_COLOR }, allow_blank: true
    validates :secondary_color, format: { with: HEX_COLOR }, allow_blank: true
  end

  def effective_primary_color
    primary_color.presence || default_primary_color
  end

  def effective_secondary_color
    secondary_color.presence || default_secondary_color
  end

  def effective_logo_url
    if logo_file.attached?
      Rails.application.routes.url_helpers.rails_blob_path(logo_file, only_path: true)
    elsif logo_url.present?
      logo_url
    else
      branding_parent&.effective_logo_url
    end
  end

  private

  def default_primary_color
    "#e53935"
  end

  def default_secondary_color
    "#ffffff"
  end

  def branding_parent
    nil
  end
end
