class MaterialSyncSource < ApplicationRecord
  SOURCE_KINDS = ['uri', 'google_drive_path', 'google_drive_file', 'legacy_drive_path'].freeze

  belongs_to :created_by_user, class_name: 'User', optional: true
  belongs_to :updated_by_user, class_name: 'User', optional: true

  validates :name, presence: true
  validates :source_kind,
            presence: true,
            inclusion: { in: SOURCE_KINDS }
  validates :profile, presence: true, inclusion: { in: MaterialExportItem::VALID_PROFILES }
  validate :source_value_must_be_present

  scope :enabled, -> { where(enabled: true) }

  def normalized_source_key
    MaterialSyncSuppression.normalize_source_key(source_kind:,
                                                 source_uri:,
                                                 source_path:,
                                                 source_file_id:)
  end

  private

  def source_value_must_be_present
    return if source_value_present?

    errors.add(:base, '同期元を指定してください．')
  end

  def source_value_present?
    case source_kind
    when 'uri'
      source_uri.present?
    when 'google_drive_file'
      source_file_id.present? || source_uri.present?
    when 'google_drive_path'
      source_file_id.present? || source_uri.present?
    when 'legacy_drive_path'
      source_path.present?
    else
      normalized_source_key.present?
    end
  end
end
