class MaterialSyncSuppressionsController < ApplicationController
  def index
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.gte_member?

    suppressions =
        MaterialSyncSuppression
        .includes(:created_by_user)
        .order(created_at: :desc, id: :desc)

    render json: { suppressions: suppressions.map { |s| repr(s) } }
  end

  def create
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.gte_member?

    suppression =
        MaterialSyncSuppressionRegistrar.create!(suppression_params,
                                                 created_by_user: current_user)

    render json: repr(suppression), status: :created
  rescue ActiveRecord::RecordInvalid => e
    render_validation_error e.record
  end

  private

  def suppression_params
    params.permit(:source_kind,
                  :source_uri,
                  :drive_path,
                  :drive_file_id,
                  :reason)
  end

  def repr suppression
    { id: suppression.id,
      source_kind: suppression.source_kind,
      source_uri: suppression.source_uri,
      drive_path: suppression.drive_path,
      drive_file_id: suppression.drive_file_id,
      normalized_source_key: suppression.normalized_source_key,
      reason: suppression.reason,
      created_by_user: suppression.created_by_user&.as_json(UserRepr::BASE),
      created_at: suppression.created_at,
      updated_at: suppression.updated_at }
  end
end
